Advertisement

Pattern library / Validation

Regex to Validate a Username

Most first-draft username rules are either too loose (^[a-z0-9_]+$ happily accepts _admin) or they smuggle in a lookahead that RE2 rejects. This one enforces the usual policy — 3–20 characters, letters/digits/_/-, starting and ending alphanumeric — with plain classes only, so it runs in JavaScript forms, Python backends and GA4/BigQuery alike.

The pattern
^[a-zA-Z0-9][a-zA-Z0-9_-]{1,18}[a-zA-Z0-9]$
Load this pattern into the tester →

How the pattern works

Test it: match & no-match examples

Every row is loaded straight into the tester — click Try to see the match live:

InputResultWhy
john_doeMatch8 chars, underscore in the middleTry →
web_dev_42Matchdigits and underscores allowed insideTry →
Jean-LucMatchhyphen inside, letters at both endsTry →
user.nameNo matchdot is not in the allowed setTry →
_adminNo matchcannot start with an underscoreTry →
abNo matchtoo short — minimum is 3 charactersTry →

Where to use it

JavaScript

const USERNAME = /^[a-zA-Z0-9][a-zA-Z0-9_-]{1,18}[a-zA-Z0-9]$/;
USERNAME.test('john_doe');   // true
USERNAME.test('_admin');      // false

Python

import re
re.fullmatch(r'[a-zA-Z0-9][a-zA-Z0-9_-]{1,18}[a-zA-Z0-9]', 'Jean-Luc')  # match
re.fullmatch(r'[a-zA-Z0-9][a-zA-Z0-9_-]{1,18}[a-zA-Z0-9]', 'user-')      # None

BigQuery / GA4 (RE2)

SELECT username,
       REGEXP_CONTAINS(username, r'^[a-zA-Z0-9][a-zA-Z0-9_-]{1,18}[a-zA-Z0-9]$') AS is_valid
FROM `project.dataset.users`
WHERE NOT REGEXP_CONTAINS(username, r'^[a-zA-Z0-9][a-zA-Z0-9_-]{1,18}[a-zA-Z0-9]$')

Common mistakes

Test this pattern on your own data
Paste it into the free tester with your real strings — nothing leaves your browser.
Open the regex tester →

FAQ

Why not just use \w+?

\w is [A-Za-z0-9_] — no hyphen, no length limit, and it happily matches a single character. It also matches inside larger strings unless you add anchors. The explicit class plus anchors states the actual policy.

How do I allow 2–32 characters instead of 3–20?

Change only the quantifier: ^[a-zA-Z0-9][a-zA-Z0-9_-]{0,30}[a-zA-Z0-9]$ gives 2–32 total. Everything else stays; the ends still forbid leading/trailing separators.

Can I use this pattern in GA4?

Yes — it is pure RE2 (no lookahead, no backreference), so GA4 and BigQuery accept it. GA4 only matches, though: to flag invalid values you filter with does not match regex, or do the validation in BigQuery with REGEXP_CONTAINS as in the snippet above. See the match types guide for which screen offers what.

Mention Regex - Match @handles in Text · Slug Regex — Match lowercase-hyphen URL Slugs · Strict Email Regex — RFC-ish Validation — Test & Copy

For GA4-specific patterns, see the GA4 regex cheat sheet, the page path regex guide, the event filter regex guide, the GA4 regex match types, the custom channel grouping guide and RE2 vs PCRE. Browse the full regex pattern library.