简体   繁体   中英

regex for MAC address

I have the following that I'm using to check for a valid MAC address

function isMacValid(mac) {
    var regexMac = /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/i
    return regexMac.test(mac);
}

This works for MAC addresses that match the standard of 6 hex values separated by either a hyphen or colon... 1a:2b:3c:4d:5e:6f or e7-f8-90-0a-1b

I now need to account for another non-standard notation of just 6 sets of hex with no separators... so 1a2b3c4d5e6f would be acceptable. How do I now make the : or - optional?

You can use [:-]? instead of [:-] .

The only problem is that 1a:2b:3c:4d:5e6f and 1a-2b:3c:4d:5e:6f will pass the check. So to avoid that I suggest you to change :

var regexMac = /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/i

with

var regexMac = /^((([0-9A-F]{2}:){5})|(([0-9A-F]{2}-){5})|([0-9A-F]{10}))([0-9A-F]{2})$/i

It's less beautifull but works

var regexMac = /^([0-9a-fA-F]{2}\W){6}$/i

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