The Pattern
``regex
^(?=.{3,20}$)[a-zA-Z0-9](?:[a-zA-Z0-9_]|\.(?!\.))*[a-zA-Z0-9]$
`
Flags: gm ā multiline, so ^ and $ anchor to each line rather than the whole input.
What It Accepts and Rejects
| Input | Result |
|---|---|
ada_lovelace | ā matches |
ada.lovelace | ā matches |
ab | ā rejected |
.leading | ā rejected |
double..dot | ā rejected |
The Lookahead Does the Length Check
(?=.{3,20}$) asserts the total length without consuming anything, which lets the rest of
the pattern describe structure independently. Trying to encode both length and structure in
one expression produces something far harder to read and to change.
The body then enforces three rules: it must start and end with a letter or digit, may
contain underscores and dots in the middle, and may not contain two dots in a row ā
\.(?!\.) is the negative lookahead that blocks double..dot.
The Limits of This Pattern
Character rules like these exclude most of the world's names. If usernames are display
names rather than identifiers, restricting to ASCII is a decision with real consequences for
who can sign up. Consider allowing Unicode letters via \p{L} with the u flag, and
normalising to NFC before storage so visually identical names cannot both be registered.
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 = /^(?=.{3,20}$)[a-zA-Z0-9](?:[a-zA-Z0-9_]|\.(?!\.))*[a-zA-Z0-9]$/gm;