Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts position at start of the string | Start of 'abc-123' |
[a-z0-9] |
Character class: matches any lowercase letter (a-z) or digit (0-9) | a, b, 1, 9 |
+ |
Quantifier: matches one or more of the preceding token (greedy) | abc, 123, a1b2 |
(?: |
Non-capturing group start: groups tokens without capturing | Start of '-(a-z0-9)+' segment |
- |
Literal hyphen: matches a hyphen character | - |
[a-z0-9] |
Character class: matches any lowercase letter (a-z) or digit (0-9) | a, b, 1, 9 |
+ |
Quantifier: matches one or more of the preceding token (greedy) | abc, 123, a1b2 |
) |
Non-capturing group end | End of '-(a-z0-9)+' segment |
* |
Quantifier: matches zero or more of the preceding non-capturing group (greedy) | No hyphen, '-abc', '-123-456' |
$ |
Anchor: asserts position at end of the string | End of 'abc-123' |
Matches
abc123a1b2abc-123a-b-c-1-2-3a1-b2-c31a
Does not match
ABCabc_123abc--123-abcabc-abc 123a b ca..b..c
Common pitfalls
- Case sensitivity: uppercase letters are not matched by [a-z]
- Hyphen placement: strings starting or ending with hyphens are invalid
- Empty strings: not matched due to '+' quantifier
- Underscores or other special characters are not allowed
Performance notes
The pattern is efficient as it avoids catastrophic backtracking. The non-capturing group (?:...) is used to improve performance by avoiding unnecessary capture. The anchors ^ and $ ensure the entire string is matched, preventing partial matches.