Regex for alphanumeric
^[a-zA-Z0-9]+$ matches letters and digits only, with no spaces or symbols. \w is close but also allows the underscore, since it equals [a-zA-Z0-9_]. To allow Unicode letters and digits use ^[\p{L}\p{N}]+$ with the u flag.
Syntax
/^[a-zA-Z0-9]+$/Examples
["abc123", "abc_123", "abc 123"].map(s => /^[a-zA-Z0-9]+$/.test(s))Result: [true, false, false]
/^\w+$/.test("abc_123")Result: true
\w allows the underscore.
"Hello World! 2024".toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")Result: "hello-world-2024"
Make a slug: replace runs of non-alphanumerics with a dash, then trim dashes.
/^[\p{L}\p{N}]+$/u.test("Straße2")Result: true
Common mistakes
- Using \w and being surprised that underscores pass; write [a-zA-Z0-9] when they should not.
- Writing [a-z0-9] without the i flag, which rejects uppercase letters.
- Placing a hyphen in the middle of the class, as in [a-z0-9-_], which creates a range from 9 to _ that includes punctuation; put the hyphen first or last.
- Forgetting the + and matching a single character only.
Practice Regex for alphanumeric
These drills check your answer on live data, free, no account needed.
- SKU codesThe whole line must match. A SKU is three capital letters, a hyphen and four digits, optionally followed by a hyphen and a size: XS, S, M, L or XL.
- URL slugsThe whole line must match. Match a URL slug: lowercase letters and digits in chunks joined by single hyphens. No hyphen at the start or end and no doubled hyphens.
- Ranges: a letter and two digitsThe whole line must match. Match one lowercase letter followed by exactly two digits, like a12.
Questions
What is the regex for alphanumeric with spaces?
^[a-zA-Z0-9 ]+$. To forbid leading and trailing spaces use ^[a-zA-Z0-9]+(?: [a-zA-Z0-9]+)*$.
What is the regex for alphanumeric and underscore?
^\w+$ in JavaScript, or ^[a-zA-Z0-9_]+$ to be explicit and portable.
How do I check for alphanumeric in Excel or SQL?
Excel 365: =REGEXTEST(A1, "^[a-zA-Z0-9]+$"). PostgreSQL: col ~ '^[a-zA-Z0-9]+$'. MySQL: col REGEXP '^[a-zA-Z0-9]+$'. See the Excel and SQL pages for details.
Related
- Regex for letters onlyThe ^[a-zA-Z]+$ pattern for ASCII letters, a Unicode version with \p{L} and the u flag, allowing spaces between words, and stripping non-letters from text.
- Regex for numbers onlyThe ^\d+$ pattern for digits-only strings, stripping everything that is not a digit, extracting numbers from text, and patterns for signed and decimal values.
- Regex for usernameUsername regex patterns: the basic ^[a-zA-Z0-9_]{3,16}$ rule, a stricter letter-first variant, pulling @handles out of text, and a Unicode-friendly version.
- Character classesWhat a character class matches, how ranges and negation work, what \d \w \s and their uppercase opposites mean, and what the dot does and does not match.