Start free · Free tools · Fair usage limits
Browse Tools

Categories

Custom AI Solutions – AI2Flows
LIVE NEWS
Loading latest AI & SEO news…
Home›Tools›Regex Tester›Regex for username
Regex pattern · validation

Regex for username

Regex for username: a tested pattern with examples, a plain-English breakdown, and code for JavaScript, Python, PHP, Java and Go.

Quick answer

Use /^[A-Za-z0-9][A-Za-z0-9._]{1,28}[A-Za-z0-9]$/ as an username regex. It matches "john_doe" and "jane.doe99", and rejects "ab" and "_john". Adjust {1,28} for different lengths ({1,28} gives 3–30).

Last updated · Maintained by FreeAIToolz · How we test

/^[A-Za-z0-9][A-Za-z0-9._]{1,28}[A-Za-z0-9]$/
  • john_doematches
  • jane.doe99matches
  • abcmatches
  • abno match
  • _johnno match
  • john_no match
  • john doeno match
  • thisusernameiswaytoolongforthisno match
Open in the full Regex Tester (replace, flags, groups) →

How this regex works

PartMeaning
^[A-Za-z0-9]first character is a letter or digit
[A-Za-z0-9._]{1,28}middle: letters, digits, dot or underscore
[A-Za-z0-9]$last character is a letter or digit (3–30 characters total)

Examples

InputResult
john_doe✓ Matches
jane.doe99✓ Matches
abc✓ Matches
ab✗ No match
_john✗ No match
john_✗ No match
john doe✗ No match
thisusernameiswaytoolongforthis✗ No match

Every example above is checked automatically in JavaScript and Python each time the site is built.

Limitations and edge cases

Adjust {1,28} for different lengths ({1,28} gives 3–30). Also check reserved names (admin, support) and uniqueness in the database.

When to use this pattern

Sign-up forms and profile settings.

Use it in your language

JavaScript

const re = /^[A-Za-z0-9][A-Za-z0-9._]{1,28}[A-Za-z0-9]$/;
re.test(input); // true or false

Python

import re
pattern = re.compile(r'^[A-Za-z0-9][A-Za-z0-9._]{1,28}[A-Za-z0-9]$')
bool(pattern.search(value))

PHP

$ok = preg_match('~^[A-Za-z0-9][A-Za-z0-9._]{1,28}[A-Za-z0-9]$~', $value) === 1;

Java

Pattern pattern = Pattern.compile("^[A-Za-z0-9][A-Za-z0-9._]{1,28}[A-Za-z0-9]$");
boolean ok = pattern.matcher(value).find();

Go

re := regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._]{1,28}[A-Za-z0-9]$`)
ok := re.MatchString(value)

More regex patterns

Frequently asked questions

What is the regex for username?
/^[A-Za-z0-9][A-Za-z0-9._]{1,28}[A-Za-z0-9]$/. Adjust {1,28} for different lengths ({1,28} gives 3–30). Also check reserved names (admin, support) and uniqueness in the database.
Which languages does this pattern work in?
It is tested in JavaScript and Python and uses syntax that also works in PHP (PCRE) and Java. It also works in Go’s RE2 engine.
Why does the pattern start with ^ and end with $?
They anchor the match to the whole string, so "abcjohn_doexyz" cannot pass just because it contains a valid part. To search for matches inside longer text, remove ^ and $ (use \b where word boundaries help) and add the g flag.