The Pattern
``regex
^[a-z0-9]+(?:-[a-z0-9]+)*$
`
Flags: gm — multiline, so ^ and $ anchor to each line rather than the whole input.
What It Accepts and Rejects
| Input | Result |
|---|---|
how-to-write-regex | ✅ matches |
png-to-webp | ✅ matches |
How-To-Write | ❌ rejected |
trailing- | ❌ rejected |
double--dash | ❌ rejected |
One Group, Repeated
^[a-z0-9]+(?:-[a-z0-9]+)*$ reads as "a run of lowercase alphanumerics, then zero or more
occurrences of a hyphen followed by another run". That structure makes the three common slug
defects impossible by construction:
A leading or trailing hyphen cannot match, because every hyphen must be followed by a run.- A double hyphen cannot match, for the same reason.
Uppercase cannot match at all, soHow-To-Writeis rejected.
The alternative — ^[a-z0-9-]+$ — accepts -, -- and slug- without complaint.The Limits of This Pattern
The pattern validates a slug but cannot create one. Generating a slug from a title needs
transliteration (é to e, ü to ue or u depending on language), whitespace collapsing, and
truncation at a word boundary — none of which a regex does. Validate with this; generate with
a real slugify function.
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 = /^[a-z0-9]+(?:-[a-z0-9]+)*$/gm;