Regex for Username/Slug — Pattern Explained with Examples
This regex validates usernames and URL slugs — short, human-readable identifiers that contain only alphanumeric characters, underscores, and hyphens. Enforcing a length of 3–20 characters ensures identifiers are long enough to be meaningful but short enough for URLs, display names, and database keys.
The Pattern
/^[a-zA-Z0-9_-]{3,20}$/Pattern Breakdown
| Part | Meaning |
|---|---|
^ | Start of string |
[a-zA-Z0-9_-] | Allowed characters: letters (both cases), digits, underscore, hyphen |
{3,20} | Length constraint: minimum 3, maximum 20 characters |
$ | End of string |
Matches
john_doeuser123my-nameadmintest_user-1a_b
Does NOT Match
ab— only 2 characters (below minimum)a@b—@is not alloweduser name— space is not alloweduser.name— period is not allowedvery_long_username_here_123— 27 characters (above 20 max)-admin— starts with hyphen (structurally allowed but often rejected by applications)username!— exclamation mark is not allowed- `` (empty string) — no input
Language Examples
JavaScript
const usernameRegex = /^[a-zA-Z0-9_-]{3,20}$/;
console.log(usernameRegex.test('john_doe')); // true
console.log(usernameRegex.test('ab')); // false
console.log(usernameRegex.test('user name')); // false
// Sanitize input by removing disallowed characters
function sanitizeUsername(input) {
return input.replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 20);
}
console.log(sanitizeUsername('hello@world!')); // helloworld
Python
import re
username_regex = r'^[a-zA-Z0-9_-]{3,20}$'
print(bool(re.match(username_regex, 'john_doe'))) # True
print(bool(re.match(username_regex, 'ab'))) # False
print(bool(re.match(username_regex, 'user name'))) # False
# Sanitize input
def sanitize_username(input_str):
cleaned = re.sub(r'[^a-zA-Z0-9_-]', '', input_str)
return cleaned[:20]
print(sanitize_username('hello@world!')) # helloworldCommon Pitfalls
Underscore vs hyphen handling — Both are allowed by this pattern, but some systems treat them differently. Hyphens are common in URLs (SEO-friendly slugs), while underscores are more common in programming identifiers. Choose based on your use case.
Minimum length varies — 3 characters is common for display names, but some systems require 4, 5, or 6 characters minimum. Social media platforms often require 3+ characters. Adjust the lower bound (
{3,20}) as needed.Starting character rules — This pattern allows usernames starting with
_or-, but many applications prohibit this because it looks like an admin/system account (e.g.,_hidden,-root). Check for this separately if needed.Unicode/emoji username support — This pattern only accepts ASCII characters. If your application needs international usernames (e.g., Chinese, Cyrillic, or accented characters), use the
uflag and Unicode property escapes like\p{L}.
Real-World Use Cases
- User registration — Creating unique display names and login identifiers
- URL slug generation — Creating SEO-friendly URLs from blog post titles (e.g.,
my-awesome-post) - Mentions and tagging — Implementing
@usernamemention systems in social applications
FAQ
Related Patterns
- Regex for Password Strength
- Regex for File Extension
- Regex for Hex Color Codes
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro