6

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 e.g

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. i.e for dot(.) find 5 instead of mix pattern same for dash(-) and colon

Community
  • 1
  • 1
Hkachhia
  • 4,463
  • 6
  • 41
  • 76

4 Answers4

9
^[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

vks
  • 67,027
  • 10
  • 91
  • 124
  • 3
    I have used this regex in my javascript but it did not work for me – Hkachhia Mar 24 '15 at 12:53
  • AA.BB.CC.DD.EE.FF I think regex check case sensative string – Hkachhia Mar 24 '15 at 12:58
  • How to use i in regex . i dont know. can i add I in regex ? if yes the where ? – Hkachhia Mar 24 '15 at 13:02
  • @Harry Javascript var re = /^[0-9a-f]{1,2}([\.:-])(?:[0-9a-f]{1,2}\1){4}[0-9a-f]{1,2}$/gmi; – vks Mar 24 '15 at 13:27
  • This regular expression fails to match capital letters. It also matches MAC addresses with just one letter or number in every position (which are invalid). – diazdeteran Apr 28 '18 at 19:26
  • @diazdeteran var re = /^[0-9a-f]{1,2}([\.:-])(?:[0-9a-f]{1,2}\1){4}[0-9a-f]{1,2}$/gmi; for single character you can change 1,2 to 2 – vks Apr 28 '18 at 19:47
4

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
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
4
\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.

Selim Ekizoglu
  • 519
  • 5
  • 6
2

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 (i.e. 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}$
diazdeteran
  • 1,144
  • 1
  • 13
  • 25