Oleg Sh
Oleg Sh

Reputation: 9013

Regex MacAddress: exclude fake values

I use regex ^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$ and it works fine.

Problem is that sometimes I get fake values like: 00:00:00:00:00:00.

I tried to search algorithms and understood, that there are no clear algo for validation. But I want to exclude explicit fake values like 00:00:00:00:00:00, 11:11:11:11:11:11... 99-99-99-99-99-99

Could somebody help me with such regex, which found such values? Thanks

Upvotes: 1

Views: 86

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627044

You can use

^(?!(\d)(?:[:-]?\1)*$)([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$

See the regex demo.

You may get rid of capturing groups using ^(?!(\d)(?:[:-]?\1)*$)(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}$.

Details

  • ^ - start of string
  • (?!(\d)(?:[:-]?\1)*$)
  • (?:[0-9A-Fa-f]{2}[:-]){5} - five repetitions of two hex chars followed with : or -
  • [0-9A-Fa-f]{2} - two hex chars
  • $ - end of string.

Upvotes: 1

Related Questions