New blogMaking an AI Agent You Can Trust With Money

★ Identity & contact · regex

Regex for Username

A common handle rule: starts with a letter, 3 to 16 characters, letters, digits and underscores. Adjust the length range to your product.

  • Runs in your browser
  • No signup

Try the username pattern

Read it in plain English (best-effort)

  • ^start of a line
  • [a-zA-Z]one character from: a–z, A–Z
  • [a-zA-Z0-9_]one character from: a–z, A–Z, 0–9, '_'
  • {2,15}between 2 and 15 of the previous
  • $end of a line

One sample per line works well with the m flag on anchored patterns.

Waiting for a pattern
01

The pattern, piece by piece

/^[a-zA-Z][a-zA-Z0-9_]{2,15}$/
Pattern explanation
PartWhat it does
^[a-zA-Z]must start with a letter
[a-zA-Z0-9_]{2,15}2–15 more letters, digits or underscores
$3 to 16 characters in total
02

What it accepts and rejects

Every sample below is checked automatically in JavaScript and Python. The tester above is preloaded with all of them, one per line.

Should match
Should match
himanshu✓
dev_42✓
Ab_c✓
jane_doe_2026✓
abc✓
A1234567890123_x✓
Should not match
Should not match
ab✗
1user✗
user name✗
user-name✗
_user✗
averyveryverylongusername✗
03

Copy it into your code

RE2-safeNo lookarounds or backreferences, so the same pattern works in Go's RE2 engine and in Rust's regex crate.

const usernameRe = /^[a-zA-Z][a-zA-Z0-9_]{2,15}$/;

export function isValidUsername(value) {
  return usernameRe.test(value.trim());
}
04

When not to use regex for this

Uniqueness, reserved words (admin, support) and case-insensitive collisions (Jane vs jane) need a database check, not a pattern. Lowercase usernames before storing to avoid look-alikes.

05

Questions engineers actually ask

Should usernames be case-sensitive?
Display them as typed, but compare and store a lowercase version to prevent near-duplicates.
Why must it start with a letter?
It avoids handles that look like IDs or numbers and keeps URLs readable.
What is catastrophic backtracking?
Some patterns, usually nested quantifiers like (a+)+, make a backtracking engine try an exponential number of paths on input that almost matches. The tester stops any run after 300ms, so a bad pattern can't freeze your tab. In production, that same pattern can take down a server (a ReDoS attack).
06

More identity & contact patterns

07

More from the workbench

Fine print

Tools: on the house.
Engineer: by the hour.

The regex was free. Code that doesn't need one is the upgrade: typed schemas, validated once at the edge, trusted everywhere after.

I'm Himanshu, an AI and full-stack engineer. I build MVPs, AI agents and the growth plumbing around them for early-stage startups.