Skip to content
Regex for Username/Slug — Pattern Explained with Examples

Regex for Username/Slug — Pattern Explained with Examples

DodaTech Updated Jun 20, 2026 3 min read

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

PartMeaning
^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_doe
  • user123
  • my-name
  • admin
  • test_user-1
  • a_b

Does NOT Match

  • ab — only 2 characters (below minimum)
  • a@b@ is not allowed
  • user name — space is not allowed
  • user.name — period is not allowed
  • very_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!'))  # helloworld

Common Pitfalls

  1. 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.

  2. 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.

  3. 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.

  4. 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 u flag 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 @username mention systems in social applications

FAQ

The regex matches both cases, but you should normalize to lowercase before storage: username.toLowerCase() (JS) or username.lower() (Python). This prevents duplicate usernames like JohnDoe and johndoe.
Dots are common in display names but can cause issues in routing and email-style identifiers. If you allow dots, extend the character set: [a-zA-Z0-9_.-]. Be aware that dots in usernames can confuse domain-like addressing (user.name could be misread as a hostname).

Related Patterns

Previous Regex for Password Strength — Pattern Explained with Examples Next Regex for File Extension — Pattern Explained with Examples

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro

Home Browse Regex Pattern Library