简体   繁体   中英

MAC address regex for JavaScript

I have get Javascript regex from this Regex link. But its match also mix pattern of MAC address

/^([0-9a-f]{1,2}[\.:-]){5}([0-9a-f]{1,2})$/i

For eg

AA-BB.CC.DD.EE.FF  

as per above regex its true but i want to match same quantifier in whole mac address. As per my requirement above mac address is wrong.

So would please help me how to match same quantifier. ie for dot(.) find 5 instead of mix pattern same for dash(-) and colon

^[0-9a-f]{1,2}([\.:-])(?:[0-9a-f]{1,2}\1){4}[0-9a-f]{1,2}$

Try this.See demo.

https://regex101.com/r/tJ2mW5/12

Change your regex like below.

^[0-9a-f]{1,2}([\.:-])[0-9a-f]{1,2}(?:\1[0-9a-f]{1,2}){4}$

case-insensitive modifier i heps to do a case-insensitive match.

DEMO

> /^[0-9a-f]{1,2}([.:-])[0-9a-f]{1,2}(?:\1[0-9a-f]{1,2}){4}$/i.test('AA-BB.CC.DD.EE.FF')
false
> /^[0-9a-f]{1,2}([.:-])[0-9a-f]{1,2}(?:\1[0-9a-f]{1,2}){4}$/i.test('AA.BB.CC.DD.EE.FF')
true
\b([0-9A-F]{2}[:-]){5}([0-9A-F]){2}\b

\\b is an anchor like the ^ and $ that matches at a position that is called a "word boundary".

[0-9A-F] is a character set that's repeated {2} times. After the character set there's : or - and the grouping ([0-9A-F]{2}[:-]) is repeated {5} times which gives us ex: 2F:3D:A9:B6:3F: . Then again we have the same character set [0-9A-F] that is repeated {2} times.

The answers provided are fine, but I would add lowercase letters and the dot (.) separator. Also, MAC addresses with just one letter or number in every position are invalid.

Here's a regular expression that matches numbers, capital and lowercase letters, checks for two characters in every position, and allows a semicolon (:), dash (-) or dot (.) as a separator.

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

The regular expression below will also match a MAC address without a delimiter (ie a MAC address like AABBCCDDEEFF), since some vendors represent MAC addresses without a separator.

^([0-9a-fA-F]{2}[:.-]?){5}[0-9a-fA-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