简体   繁体   中英

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_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:

[[ "$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.

^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM