Regex for username

Use /^[A-Za-z][A-Za-z0-9_]{2,15}$/ to check that a whole string is a valid for username. Every example below is tested against the pattern, and you can open it in the Regex Tester with the samples preloaded.

Updated

/^[A-Za-z][A-Za-z0-9_]{2,15}$/
Open in Regex Tester
InputResult
john_doe✓ Match
Dev2026✓ Match
abc✓ Match
2cool✗ No match
ab✗ No match
john.doe✗ No match
this_name_is_too_long✗ No match

How the pattern works

PartMeaning
^[A-Za-z]Must start with a letter
[A-Za-z0-9_]{2,15}2–15 more letters, digits or underscores (3–16 characters in total)
$End of the string

Code examples

JavaScript

const re = /^[A-Za-z][A-Za-z0-9_]{2,15}$/;
re.test(value); // true or false

Python

import re

bool(re.fullmatch(r'[A-Za-z][A-Za-z0-9_]{2,15}', value))

PHP

preg_match('/^[A-Za-z][A-Za-z0-9_]{2,15}$/', $value) === 1;

Notes and limitations

Adjust the length and character set to your rules, and compare usernames case-insensitively so “Admin” and “admin” can’t both register.

Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool

Frequently asked questions

What is the regex for username?
/^[A-Za-z][A-Za-z0-9_]{2,15}$/ — it matches the whole string. See the table above for what each part does.
Which examples match?
Of the examples tested, these match: john_doe, Dev2026, abc. The others don’t.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.