Regex for multiple MAC addresses separated by comma?
I would like to know the correct regex for matching multiple MAC addresses separated my any delimiter, such as a comma. 开发者_StackOverflow社区
The regex for a single MAC address would be: ^([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}$
.
So for multiple MAC addresses delimited by comma, i figured ^(([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2},?)){+}$
would do the trick.
Where am i going wrong? Any help would be appreciated, thanks.
Edit: Some people have asked about what went wrong. Well, simply put, the regex does not work. Let us say i enter a single (valid) MAC address, it is flagged as an invalid MAC address. Same goes for multiple MAC addresses delimited by comma.
The regex is needed for a validator for a textbox on an ASP .NET page. If more details are needed, let me know.
^([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}(,([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2})*$
See Regex for Comma delimited list for details about making a regex to match a delimited list. Basically you need to put the regex for a MAC address followed by a group containing a comma and the regex for a MAC address that is matched zero or more times. In your attempted solution the comma is completely optional.
Try this ^([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}(,([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2})+
^(?:((?:[a-fA-F0-9]{2}[-:]){5}(?:[a-fA-F0-9]{2}))(?:,|$)))+$
This ensures the octets is delimited by :
or -
. No spaces or other characters are allowed. The first group will capture all the mac addresses. The match will capture the whole string, or fail to match if it isn't valid.
精彩评论