Regex and cron

Regex for Usernames

A username rule set that keeps handles readable and URL-safe, enforced by one pattern.

  • Free foreverNo trial, no paywall, no usage limits.
  • No sign-upOpen the page and start. We never ask for an email to use a tool.
  • PrivateEverything runs in your browser. Your input is never uploaded or stored on our servers.
  • Works offlineOnce the page has loaded, the tool keeps working without a connection.

Pattern

/^(?=.{3,16}$)[A-Za-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$/

Regular expression

JavaScript syntax, run by your browser's own engine in a background worker. Press / anywhere to jump here.
Reset to the original pattern and examplesShow cheat sheet: click any token to insert itCopy pattern
Find every match instead of stopping at the first. Needed for matchAll() and for replacing all occurrences.Case-insensitive: /abc/i also matches "ABC" and "aBc".^ and $ match at the start and end of every line, not just the whole string. Use it to test one value per line.Lets . match line breaks too. Without it, . stops at \n and \r.Treats the pattern as Unicode code points: enables \p{…} property escapes and \u{…}, makes emoji count as one character, and rejects sloppy escapes.Only matches starting exactly at lastIndex (position 0 here), never further along. Useful for tokenizers that consume input piece by piece.Records the start and end index of every capture group (match.indices). The tester always shows group positions, so this only changes your code.The upgraded unicode mode (ES2024): set operations like [\p{L}--[a-z]] and [A&&B], string properties like \p{RGI_Emoji}. Cannot be combined with u.
5 matches5 matches

Test string

Matches are highlighted as you type, in alternating colors. Click inside a match (or hover its row below) to color its capture groups.
5 matchesClear test string

Explanation

Every part of the pattern in plain English. Hover a row to highlight that part of the pattern.
Copy explanation

Loading the explainer…

Every match with its position and capture groups.Preview a replacement with $1, $<name> and $& references, then copy the result.Copy a ready-to-run snippet for JavaScript, Python, Go, C#, PHP or Dart.

Matches

Named groups are shown by name. undefined means the group did not take part in that match.
Copy matches as JSONDownload matches.csv
#MatchPosition
1jane_doe0–8
2john.smith9–19
3player-one20–30
4dev4231–36
5abc37–40

Need a secure web app built around this? Talk to our team

Quick answer

A good username regex is ^(?=.{3,16}$)[A-Za-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$. It allows 3 to 16 characters, requires a letter first, and permits single dots, underscores or hyphens only between letters and digits, so jane_doe and player-one pass while _jane, jane__doe and jane. fail. The lookahead at the start checks the length once, which keeps the rest of the pattern simple.

  • Tested examples
  • Token-by-token breakdown
  • Code in 5 languages
  • Live tester

How to use the username regex

  1. 1Copy the pattern with Copy pattern in the tester, or take a ready-made snippet for your language from the code section below.
  2. 2Check the sample lines in Test string: every line the username regex accepts is highlighted, rejected lines stay plain.
  3. 3Paste your own values one per line to see which pass, and read Explanation for what each part of the pattern does.
  4. 4Open the Code tab for JavaScript, Python, Go, C#, PHP or Dart with the pattern translated and escaped.
  5. 5Validate again on the server: client-side checks give users quick feedback, not security.

How does the username regex work?

Read it left to right. Each piece below matches one part of the input:

  • ^ Start of the string.
  • (?=.{3,16}$) Lookahead: the whole username is 3 to 16 characters. It checks without consuming, so matching restarts at the beginning.
  • [A-Za-z] The first character must be a letter, so handles never look like numbers or flags.
  • [A-Za-z0-9]* Any letters and digits after it.
  • (?:[._-][A-Za-z0-9]+)* Optional groups of one separator followed by letters or digits. Separators can never be doubled or come last.
  • $ End of the string.

Which strings does the username regex match?

The whole input must match, from the first character to the last. Every row below is checked against the pattern by our automated test suite before each release.

InputMatches?Why
jane_doeYesUnderscore between two words.
john.smithYesA single dot is allowed between parts.
player-oneYesHyphens work the same way.
dev42YesDigits are fine after the first letter.
abcYesThe minimum length of 3.
abNoToo short.
1playerNoMust start with a letter.
jane__doeNoTwo separators in a row.
jane_NoCannot end with a separator.
_janeNoCannot start with a separator.
this_username_is_too_longNo25 characters: over the 16-character limit.
jane doeNoSpaces are not allowed.
janéNoAccented letters are outside A–Z (see the Unicode variant below).

How do I change the username rules?

Each rule lives in one place, so adjust the part you need:

RuleChange
Length 3–30(?=.{3,30}$)
Allow a digit firstreplace [A-Za-z] with [A-Za-z0-9]
Underscores onlyreplace [._-] with _
Lowercase onlydrop A-Z from both classes
Any script (Unicode letters)[\p{L}][\p{L}\p{N}]*(?:[._-][\p{L}\p{N}]+)* with the u flag

Two rules belong in code, not in the regex: reserved names (admin, support, root, api, your brand) and uniqueness. Compare usernames case-insensitively, and if you allow Unicode, normalize with NFKC first so look-alike characters cannot impersonate another user.

Why use a lookahead for the length?

Without it you would have to count characters across the separators, which regex is bad at. (?=.{3,16}$) checks the total length once, at the start, and consumes nothing: the rest of the pattern then only describes the shape.

Go's RE2 engine does not support lookaheads. In Go, drop the lookahead and check len(username) (or utf8.RuneCountInString) in code, which is clearer anyway.

How do I use the username regex in JavaScript, Python, Go, C# and PHP?

The pattern is translated for each engine rather than pasted as is: named groups, anchors, escapes, shorthand classes and flags are adjusted so each snippet behaves as closely to the JavaScript version as its engine allows. Differences that remain (Go's RE2 has no lookarounds or backreferences, for example) are called out under each one. The Code tab in the tester above also exports Dart, and updates as you edit the pattern.

JavaScript and TypeScript

const regex = /^(?=.{3,16}$)[A-Za-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$/;

function isValid(value) {
  return regex.test(value);
}

console.log(isValid("jane_doe"));

Python

import re

pattern = re.compile(r"^(?=.{3,16}\Z)[A-Za-z][A-Za-z0-9]*(?:[._\-][A-Za-z0-9]+)*\Z")

def is_valid(value: str) -> bool:
    return pattern.search(value) is not None

print(is_valid("jane_doe"))
  • JavaScript's . also refuses \r, \u2028 and \u2029; in Python it only refuses \n.
  • JavaScript's $ only matches at the very end of the string. Python's $ also matches before a trailing newline, so the pattern uses \Z instead.

Go

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`^(?=.{3,16}$)[A-Za-z][A-Za-z0-9]*(?:[._\-][A-Za-z0-9]+)*$`)
	fmt.Println(re.MatchString("jane_doe"))
}

Go's regexp package (RE2) does not support lookahead or lookbehind, so this pattern will not compile. Match more broadly and check the extra condition in Go code instead.

  • JavaScript's . also refuses \r, \u2028 and \u2029; in Go it only refuses \n.

C#

using System;
using System.Text.RegularExpressions;

// The timeout stops a pathological input from hanging the thread (ReDoS).
var regex = new Regex(@"^(?=.{3,16}\z)[A-Za-z][A-Za-z0-9]*(?:[._\-][A-Za-z0-9]+)*\z", RegexOptions.None, TimeSpan.FromSeconds(1));
Console.WriteLine(regex.IsMatch("jane_doe"));
  • JavaScript's . also refuses \r, \u2028 and \u2029; in .NET it only refuses \n.
  • JavaScript's $ only matches at the very end of the string. .NET's $ also matches before a trailing newline, so the pattern uses \z instead.

PHP

<?php

$pattern = '/^(?=.{3,16}$)[A-Za-z][A-Za-z0-9]*(?:[._\-][A-Za-z0-9]+)*$/D';

function isValid(string $value, string $pattern): bool
{
    return preg_match($pattern, $value) === 1;
}

var_dump(isValid('jane_doe', $pattern));
  • JavaScript's . also refuses \r, \u2028 and \u2029; in PHP (PCRE) it only refuses \n.
  • The D modifier makes $ match only at the very end, like JavaScript (PCRE's $ also matches before a trailing newline).

Browse all 25 patterns in the regex pattern library, or build your own in the regex tester.

Frequently asked questions

Letters and digits, plus at most one kind of separator such as underscore, dot or hyphen, used singly between characters. That keeps usernames readable, safe in URLs and hard to confuse with each other.
Keep a list of reserved names and check it in code after the regex passes, comparing in lowercase. A regex that excludes specific words becomes unreadable quickly.
Store them as typed for display, but compare and enforce uniqueness in lowercase, otherwise JaneDoe and janedoe become two different accounts that look the same.

Last updated by the Playxoft engineering team.

From the engineers who built this tool

Building something bigger than a quick fix?

Auth, payments, dashboards and security are where web apps get hard. We have shipped them many times. Share your idea and we will map out a realistic plan and estimate, free and with no obligation.

More free tools

See all tools

Regex Tester

Test regex live with highlighted matches, plain-English explanations and code export.

Open tool

Cron Expression Generator

New

Build and explain cron schedules, see the next runs in any time zone, copy platform snippets.

Open tool

SQL Formatter

Beautify or minify SQL in 12 dialects, with keyword case, indent and line:column errors.

Open tool

cURL to Python Converter

New

Convert cURL commands into Python requests or httpx code with params, json, files and auth.

Open tool

cURL to Fetch Converter

New

Turn any cURL command into JavaScript fetch() code with headers, JSON, forms and auth.

Open tool

cURL to Axios Converter

New

Convert cURL commands into an Axios request config with params, data, auth and timeouts.

Open tool