简体   繁体   中英

Regex matching MAC address

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.

  • You have to remove the anchors ^ and $

  • You have to add az 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

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 (AF), 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 "af" after the AF.

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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM