Regex tester · Guide

Regex Match Alphanumeric: Letters and Digits Only

Alphanumeric validation is one of the most common regex tasks and has two traps: `\w` is not alphanumeric, and "letter" means different things depending on the engine and the flags.

The underscore problem

\w is shorthand for [A-Za-z0-9_] — it includes the underscore. If you want strictly letters and digits, spell it out:

Regex
^[A-Za-z0-9]+$      # strictly alphanumeric, ASCII
^\w+$               # also allows underscore
^[[:alnum:]]+$      # POSIX class, same as the first

This matters for identifiers, slugs and filenames where the underscore is either required or forbidden. Being explicit documents which it is.

Unicode letters

[A-Za-z] excludes every accented and non-Latin letter, so a name like "Zoë" or "Олена" fails validation. That is a real usability problem, not an edge case.

Use Unicode property escapes where supported:

Regex
^[\p{L}\p{N}]+$        # any Unicode letter or number

This needs the u flag in JavaScript, re.UNICODE (the default) in Python 3, and works natively in Java, .NET and PCRE. In Python the regex package is required for full \p{...} support.

Practical variants

A URL slug allows hyphens but not leading or trailing ones: ^[a-z0-9]+(?:-[a-z0-9]+)*$. A username often allows underscores and a length range: ^[A-Za-z0-9_]{3,20}$.

A general rule for user-facing fields: be permissive about what you accept and strict about how you store it. Rejecting a legitimate name because of an apostrophe or an accent is a worse outcome than normalising it.

Frequently asked questions

Does \w mean alphanumeric?

No — it includes the underscore. Use [A-Za-z0-9] for strictly alphanumeric.

How do I allow accented letters?

Use \p{L} with Unicode support enabled (the u flag in JavaScript).

Should I validate names as alphanumeric?

Generally no. Real names contain spaces, apostrophes, hyphens and non-Latin characters.

Ready to try it?

Open the free browser-based Regex tester and apply what you just read — no sign-up, runs locally.

Open the Regex tester tool