Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | Start of 'abc123' |
[ |
Start of a character class | N/A |
a-z |
Range: lowercase letters a through z | a, b, ..., z |
A-Z |
Range: uppercase letters A through Z | A, B, ..., Z |
_ |
Literal underscore character | _ |
] |
End of the character class | N/A |
[ |
Start of a second character class | N/A |
a-z |
Range: lowercase letters a through z | a, b, ..., z |
A-Z |
Range: uppercase letters A through Z | A, B, ..., Z |
0-9 |
Range: digits 0 through 9 | 0, 1, ..., 9 |
_ |
Literal underscore character | _ |
] |
End of the character class | N/A |
* |
Quantifier: zero or more of the preceding element (the character class) | No characters, 'a', '1_', etc. |
$ |
Anchor: asserts position at end of the string | End of 'abc123' |
Matches
aA_abcABC_123var_namexhello_world123
Does not match
1abcabc!abc defabc@123123a ba-b
Common pitfalls
- Forgetting the ^ anchor may allow leading digits or other invalid characters.
- Assuming this matches all valid JavaScript identifiers (e.g., fails for Unicode identifiers like 'é' or '$').
- Overlooking that * allows zero occurrences, so empty string matches if not for ^ and $ anchors.
- Confusing with regexes that allow hyphens or other special characters in identifiers.
Performance notes
No catastrophic backtracking risk due to simple quantifiers and character classes. Efficient for typical use cases. Anchors ensure linear scanning.