Domanda

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

È stato utile?

Soluzione

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"

Altri suggerimenti

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}$
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top