[英]BASH regex match MAC address
I'm trying to allow a user to only input a valid mac address (ie 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.
我已经尝试了我能想到的一切,我很确定这样的事情是可能的。
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 ver
3.1
上使用正则表达式,你需要引用正则表达式,所以下面应该工作:
[[ "$MAC_ADDRESS" =~ "^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$" ]] && echo "valid" || echo "invalid"
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}$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.