BASH 正则表达式匹配 MAC 地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19959537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
BASH regex match MAC address
提问by user2988671
I'm trying to allow a user to only input a valid mac address (i.e. 0a:1b:2c:3d:4e:5f), and would like it to be more succinct than the expanded form:
我试图让用户只输入一个有效的 mac 地址(即 0a:1b:2c:3d:4e:5f),并希望它比扩展形式更简洁:
[[ $MAC_ADDRESS =~ [a-zA-Z0-9][a-zA-Z0-9]:[a-zA-Z0-9][a-zA-Z0-9]:[a-zA-Z0-9][a-zA-Z0-9]:[a-zA-Z0-9][a-zA-Z0-9]:[a-zA-Z0-9][a-zA-Z0-9] ]]
Is there a way to do it like this?
有没有办法做到这一点?
[[ $MAC_ADDRESS =~ ([a-zA-Z0-9]{2}:){5}[a-zA-Z0-9]{2} ]]
Essentially, I'd like to create a "group" consisting of two alphanumeric characters followed by a colon, then repeat that five times. I've tried everything I can think of, and I'm pretty sure something like this is possible.
本质上,我想创建一个由两个字母数字字符后跟一个冒号组成的“组”,然后重复五次。我已经尝试了我能想到的一切,而且我很确定这样的事情是可能的。
回答by anubhava
I would suggest using ^
and $
to make sure nothing else is there:
我建议使用^
并$
确保没有其他东西:
[[ "$MAC_ADDRESS" =~ ^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$ ]] && echo "valid" || echo "invalid"
EDIT:For using regex on BASH ver 3.1
you need to quote the regex, so following should work:
编辑:要在 BASH 版本上使用正则表达式,3.1
您需要引用正则表达式,因此以下应该有效:
[[ "$MAC_ADDRESS" =~ "^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$" ]] && echo "valid" || echo "invalid"
回答by Andy
You are actually, very close on your suggestion. Instead of going A to Z, just go A to F.
你实际上非常接近你的建议。与其从 A 到 Z,不如从 A 到 F。
^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$