The Pattern
``regex
^(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}$
`
Flags: gm ā multiline, so ^ and $ anchor to each line rather than the whole input.
What It Accepts and Rejects
| Input | Result |
|---|---|
00:1B:44:11:3A:B7 | ā matches |
00-1b-44-11-3a-b7 | ā matches |
001B44113AB7 | ā rejected |
00:1B:44:11:3A | ā rejected |
Six Octets, One Separator Style
The pattern repeats "two hex digits and a separator" five times and then requires a final
pair. That structure is what rejects a five-octet address, and the character class
[:-] accepts both the colon notation Unix tools use and the hyphen notation Windows
prefers.
Because the separator class is evaluated independently each time, 00:1B-44:11-3A:B7 is
also accepted. Requiring a consistent separator needs a backreference:
^([0-9A-Fa-f]{2})([:-])(?:[0-9A-Fa-f]{2}\2){4}[0-9A-Fa-f]{2}$.
The Limits of This Pattern
Cisco equipment writes MAC addresses as 001b.4411.3ab7 ā three groups of four digits
separated by dots ā which this pattern rejects. Bare twelve-digit forms are also rejected.
And a syntactically valid MAC address may still be locally administered, multicast, or
simply spoofed: the second-least-significant bit of the first octet tells you the first, and
nothing tells you the last.
Testing Before Shipping
A regex that has only been tried against inputs you expect to match is untested. Every
pattern needs three kinds of case:
1. Valid inputs that should match, including the awkward-but-legal ones.
2. Invalid inputs that should not, especially near-misses that differ by one character.
3. Adversarial inputs ā very long strings, unusual Unicode, and nesting that could
trigger catastrophic backtracking.
Paste your own examples into the tester above and watch which lines highlight. A pattern
that matches everything you throw at it is usually too permissive rather than correct.
Catastrophic Backtracking
Nested quantifiers over overlapping character classes ā (a+)+, (\w+\s?)* ā can take
exponential time on a non-matching input. On a server that is a denial-of-service bug, not a
performance issue. If a pattern is applied to user input, bound the input length first and
prefer explicit alternation over nested repetition.
Anchors, Greediness and Backtracking
Three behaviours account for most regex surprises, and this pattern shows all three.
Anchors. ^ and $ pin the match to the start and end of the input. Without them,
\d{3} matches the 123 inside abc123def. With m in the flags ā as here ā they
pin to each *line* instead, which is what lets one pattern be tested against a list.
Greediness. .* takes as much as it can and gives back only when forced; .*? takes
as little as possible. On , the pattern <.*> matches the whole string and
<.*?> matches just .
Testing It Properly
`javascript
const pattern = /^(?:[0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}$/gm;