3

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})$
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Shwetabh Shekhar
  • 2,608
  • 1
  • 23
  • 36
  • Do mixed symbols count? Such as `AD:12-13:FC-14-EE:FF:FF`? Or mixed cases like `aD:12:13:Fc:14:Ee:FF:Ff`? – Hao Wu Mar 12 '21 at 06:42
  • @HaoWu Mixed symbols do not count for any kind of mac address. I can work with mixed cases but usually, the mac address will be in one case upper or lower. – Shwetabh Shekhar Mar 12 '21 at 06:46

3 Answers3

3

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}$
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
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.

SeaBean
  • 22,547
  • 3
  • 13
  • 25
1

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.
JvdV
  • 70,606
  • 8
  • 39
  • 70