Skip to content

Regex for Username

This regex matches usernames between 3 and 20 characters containing only letters, numbers, underscores, and hyphens. This is one of the most common username format policies used across web applications. It prevents special characters that could cause issues in URLs, file paths, or SQL queries while still allowing readable, flexible usernames.

Pattern
^[a-zA-Z0-9_-]{3,20}$
Test this pattern in the Regex Tester →

What is the regex pattern for Username?

The regex pattern for Username is ^[a-zA-Z0-9_-]{3,20}$. This regex matches usernames between 3 and 20 characters containing only letters, numbers, underscores, and hyphens. This is one of the most common username format policies used across web applications. It prevents special characters that could cause issues in URLs, file paths, or SQL queries while still allowing readable, flexible usernames. This pattern is commonly used for user registration forms and profile url slugs.

Test Examples

Match
john_doe
Matches: john_doe
Match
dev-user-42
Matches: dev-user-42
No Match
ab

Common Uses

Variations

Must start with letter

^[a-zA-Z][a-zA-Z0-9_-]{2,19}$

First character must be a letter

Lowercase only

^[a-z0-9_-]{3,20}$

Enforces lowercase for URL-friendly usernames

With dots

^[a-zA-Z0-9._-]{3,20}$

Also allows periods (like GitHub)

Frequently Asked Questions

Why limit username length to 3-20 characters?

A minimum of 3 prevents meaningless usernames, and a maximum of 20 keeps them readable in UIs and URLs. These are common defaults, but you can adjust them to your application's needs.

Should usernames be case-sensitive?

Most applications treat usernames as case-insensitive to prevent confusion (e.g., JohnDoe vs johndoe). Store the original casing for display but normalize to lowercase for uniqueness checks.

Why not allow spaces or special characters?

Restricting to alphanumeric characters, underscores, and hyphens ensures usernames are safe for URLs, file paths, command-line arguments, and database queries without requiring escaping.

Related Patterns

Email Address

^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA...

URL Slug

^[a-z0-9]+(?:-[a-z0-9]+)*$

Strong Password

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!...

Related Reading

Regex Cheat Sheet with Examples for Developers → URL Encoding Special Characters →