Back to the lesson

Check MAC-address

MAC-address of a network interface consists of 6 two-digit hex numbers separated by a colon.

For instance: '01:32:54:67:89:AB'.

Write a regexp that checks whether a string is MAC-address.

Usage:

let reg = /your regexp/;

alert( reg.test('01:32:54:67:89:AB') ); // true

alert( reg.test('0132546789AB') ); // false (no colons)

alert( reg.test('01:32:54:67:89') ); // false (5 numbers, must be 6)

alert( reg.test('01:32:54:67:89:ZZ') ) // false (ZZ ad the end)

A two-digit hex number is [0-9a-f]{2} (assuming the i flag is enabled).

We need that number NN, and then :NN repeated 5 times (more numbers);

The regexp is: [0-9a-f]{2}(:[0-9a-f]{2}){5}

Now let’s show that the match should capture all the text: start at the beginning and end at the end. That’s done by wrapping the pattern in ^...$.

Finally:

let reg = /^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$/i;

alert( reg.test('01:32:54:67:89:AB') ); // true

alert( reg.test('0132546789AB') ); // false (no colons)

alert( reg.test('01:32:54:67:89') ); // false (5 numbers, need 6)

alert( reg.test('01:32:54:67:89:ZZ') ) // false (ZZ in the end)