Skip to content

Regex for Alphanumeric β€” Pattern Explained with Examples

DodaTech Updated 2026-06-20 2 min read

In this tutorial, you'll learn about Regex for Alphanumeric. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

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

Part Meaning
^ 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.

Regex for Username Regex for Password

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro