Regex matching MAC address

6.8k views Asked by At

I'm trying to get all valid MAC addresses from this string:

00:1e:68:51:4f:a9    <-> 00:1a:8c:10:ad:30          9       540       8       336      17       876    90.457130000       198.0143

I've tried this and a few other regexes:

^([0-9A-F]{2}[:]){5}([0-9A-F]{2})$

Regex 101 here:

https://regex101.com/r/kI5nI6/1

I can't figure out why I'm not getting any matches.

2

There are 2 answers

2
karthik manchala On BEST ANSWER
  • You have to remove the anchors ^ and $

  • You have to add a-z in your character set.. or make the searches case insensitive with (?i) (i modifier)

Following will work:

([0-9a-fA-F]{2}[:]){5}([0-9a-fA-F]{2})

See DEMO

2
Jake Griffin On

The anchors ^ and $ say to only match strings that are MAC addresses, not the parts within strings that are MAC addresses. Also, your regex uses capital letters (A-F), but the MAC addresses in that string are lowercase. Are you doing a case insensitive search (if using the re module, that would be re.IGNORECASE)? Try turning on case-insensitive search or add "a-f" after the A-F.

On a side note, there is no reason to include the : in brackets ([:]), because that means "match any one of this one character". You can just use : directly.

With case insensitive off you should be able to use this:

([0-9A-Fa-f]{2}:){5}([0-9A-Fa-f]{2})

With case insensitive on:

([0-9A-F]{2}:){5}([0-9A-F]{2})