Regular expression for validating 64 bit (8 byte) MAC addresses?

Viewed 232

I have already gone through questions that have answered validating mac addresses but they are exclusive to 48-bit mac addresses. I am looking for a regex that can validate 8 bytes or 64-bit mac addresses. A 64-bit mac address looks something like this:(basically has 4 more hexadecimal digits than 48 bit)

00:13:a2:00:41:8b:93:7a
0013a200418b937a
AD:12:13:FC:14:EE:FF:FF
ad-12-13-fc-14-ee-ff-ad 

Based on answers for validating 48-bit mac addresses I have come up with this but am looking for something simpler.

^((([0-9A-Fa-f]{2}:){7})|(([0-9A-Fa-f]{2}-){7})|([0-9A-Fa-f]{14}))([0-9A-Fa-f]{2})$
3 Answers

You could capture the separator with ([-:]?) which allows digits to be separated by a colon, dash, or nothing. Then for successive matches use a \1 backreference to ensure the separators are consistent. This will cut down on the repetitiveness.

^[0-9A-Fa-f]{2}([:-]?)(?:[0-9A-Fa-f]{2}\1){6}[0-9A-Fa-f]{2}$

Try this:

^((?:[0-9A-Fa-f]{2}(?:[:-]?)){7}(?:[0-9A-Fa-f]{2}))$

Regex Demo

This has factor out the 3 options with :, - and null as group separator between 2 hex digits.

It also removed unnecessary brackets and unnecessary capturing groups.

Alternatively you can turn off case-sensitivity and use a negative lookahead:

^(?!.*[_G-Z])\w\w([:-]?)(?:\w\w\1){6}\w\w$

See the online Java demo

  • ^ - Start string anchor.
  • (?!.*[_G-Z]) - Negative lookahead to prevent an underscore or any character G-Z.
  • \w\w - Match two word-characters (\w equals [0-9A-Za-z_]).
  • ([:-]?) - Capture an optional colon or hyphen.
  • (?: - Open non capture group:
    • \w\w\1 - Two word-characters and a backreference to our capture group.
    • ){6} - Close non-capture group and match 6 times.
  • \w\w - Match two word-characters.
  • $ - End string anchor.
Related