Skip to content
Regex for Alphanumeric — Pattern Explained with Examples

Regex for Alphanumeric — Pattern Explained with Examples

DodaTech Updated Jun 20, 2026 2 min read

Alphanumeric validation is a fundamental pattern used in usernames, product codes, order IDs, and many other input fields. This pattern restricts input to letters and digits only, preventing special characters, spaces, and non-ASCII symbols.

The Pattern

/^[a-zA-Z0-9]+$/

Pattern Breakdown

PartMeaning
^Start-of-string anchor
[a-zA-Z0-9]+One or more characters from the sets A-Z, a-z, or 0-9
$End-of-string anchor

Matches

  • Hello123
  • ABC
  • 12345
  • testUser99
  • ABCdef123XYZ

Does NOT Match

  • hello world (space)
  • hello!
  • user_name
  • test@email
  • 你好
  • abc-def

Language Examples

JavaScript

const alphanumericRegex = /^[a-zA-Z0-9]+$/;
console.log(alphanumericRegex.test('Hello123')); // true
console.log(alphanumericRegex.test('hello world')); // false

Python

import re
pattern = r'^[a-zA-Z0-9]+$'
print(bool(re.match(pattern, 'Hello123')))    # True
print(bool(re.match(pattern, 'hello world'))) # False

Common Pitfalls

  • This pattern does not include underscores — use [a-zA-Z0-9_] if you need underscore support for identifiers
  • Unicode letters (é, ñ, ü, Chinese, Arabic, etc.) are not matched — use \p{L} with the appropriate flag for full Unicode support
  • Leading or trailing spaces will cause rejection — decide whether to trim input before validation or use ^\s*[a-zA-Z0-9]+\s*$ if whitespace should be tolerated
  • Case sensitivity is explicit: both uppercase and lowercase are included, but removing A-Z or a-z makes the pattern case-restricted
  • Minimum length is not enforced by the + quantifier (requires at least 1) — use {n,m} for specific length requirements

Real-World Use Cases

  • Username validation — many systems restrict usernames to alphanumeric characters for consistency
  • Promo code entry — discount codes are typically alphanumeric to avoid confusion between similar characters
  • Inventory SKUs — product stock-keeping units often use alphanumeric identifiers for sorting and database indexing

FAQ

How do I make the pattern allow spaces as well?
Add a space inside the character class: ^[a-zA-Z0-9 ]+$. Be aware that leading, trailing, or consecutive spaces will also match — use ^\s*[a-zA-Z0-9]+(?:\s+[a-zA-Z0-9]+)*\s*$ for word-separator semantics.
What about allowing underscores like in programming variable names?
Add underscore to the character class: ^[a-zA-Z0-9_]+$. This is common for validating programming identifiers. Some languages also allow a leading underscore, which this modified pattern accepts.

Related Patterns

Regex for Username Regex for Password

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro