Regex for Username Validation
The standard username rule: 3 to 16 characters from letters, digits, and underscore — no spaces, no symbols that need escaping in URLs or breaking in mentions. The character class plus a bounded quantifier is the whole pattern, which makes it a good first regex to actually understand rather than paste.
/^[a-zA-Z0-9_]{3,16}$/How it works, token by token
| Token | Meaning |
|---|---|
| ^ | start of string |
| [a-zA-Z0-9_] | one allowed character: letter, digit, or underscore (equivalent to \w in ASCII mode) |
| {3,16} | between 3 and 16 of them — both bounds inclusive |
| $ | end of string — nothing else allowed |
What it matches
dev_kultUser123abcabuser namethis_username_is_way_too_longTry it live
One candidate per line — the m flag makes the ^ and $ anchors apply to each line. Edit anything; it runs in your browser.
Variations
^[a-zA-Z][a-zA-Z0-9_]{2,15}$must start with a letter — avoids all-digit names that collide with IDs^[a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?$GitHub-style: lowercase and hyphens, no leading/trailing/only hyphenLanguage notes
- \w{3,16} looks equivalent but in Python 3 \w matches unicode letters by default — use the explicit class (or re.ASCII) if you mean ASCII only.
Frequently asked questions
Why 3 to 16 characters?
Convention more than law: under 3 collides and confuses, over 16 breaks layouts and mentions. Adjust the bounds to your product — the pattern shape stays the same.
How do I forbid leading digits or trailing underscores?
Pin the first character with its own class: ^[a-zA-Z][a-zA-Z0-9_]{2,15}$ requires a letter first. For no trailing underscore, end with [a-zA-Z0-9]$ and shorten the middle quantifier by one.
Building something custom? The regex tester gives you live match highlighting for any pattern.