Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | #ABC |
# |
Literal character '#' | # |
( |
Start of a non-capturing group (or alternation group) | ( |
[ |
Start of a character class | [ |
A-F |
Range of uppercase letters A to F | A |
a-f |
Range of lowercase letters a to f | a |
0-9 |
Range of digits 0 to 9 | 0 |
] |
End of character class | ] |
{6} |
Quantifier: exactly 6 occurrences of the preceding element (hex digits) | 123456 |
| |
Alternation: matches either the preceding or following pattern | | |
[ |
Start of a character class | [ |
A-F |
Range of uppercase letters A to F | A |
a-f |
Range of lowercase letters a to f | a |
0-9 |
Range of digits 0 to 9 | 0 |
] |
End of character class | ] |
{3} |
Quantifier: exactly 3 occurrences of the preceding element (hex digits) | 123 |
) |
End of group | ) |
$ |
Anchor: asserts position at end of the string | 123 |
Matches
#abc#ABC#123#123456#a1b2c3#FFFFFF#000000#fff
Does not match
#ab#1234#GHI#12345#1234567abc#123##123
Common pitfalls
- Forgetting the '^' anchor may cause partial matches in longer strings.
- Assuming the pattern matches 4 or 5 digit hex codes (it does not).
- Overlooking case insensitivity in hex digits (e.g., '#aBc' is valid).
- Not anchoring the end with '$' may allow trailing characters (e.g., '#123abc' would match if '$' is omitted).
Performance notes
The alternation between 6 and 3 digits is safe in JavaScript as it does not introduce catastrophic backtracking. However, anchoring both start ('^') and end ('$') is critical to prevent partial matches in longer strings.