What Is a Good Regex to Match Only Letters and Numbers?
Pattern: ^[a-zA-Z0-9]+$. The alphanumeric regex ^[a-zA-Z0-9]+$ matches strings containing only ASCII letters and digits with no spaces, punctuation, or special characters allowed. It is commonly used for username validation, ID formats, API key formats, and input sanitization. For international characters including accented letters, CJK characters, and other scripts, consider Unicode-aware patterns using the \p{L} property escape.
Breaking Down the Pattern
| Part | Meaning |
|---|---|
^ | Start of string |
[a-zA-Z0-9] | One letter (upper or lower) or digit |
+ | One or more characters |
$ | End of string |
Test Cases
| Input | Match? | Note |
|---|---|---|
Hello123 | Yes | Valid format |
ABC | Yes | Valid format |
42 | Yes | Valid format |
hello world | No | Contains a space |
test@123 | No | Contains @ symbol |
Usage Examples
JavaScript
const pattern = /^[a-zA-Z0-9]+$/;
pattern.test('Hello123'); // true
pattern.test('hello world'); // false
Python
import re
pattern = r'^[a-zA-Z0-9]+$'
bool(re.match(pattern, 'Hello123')) # True
bool(re.match(pattern, 'hello world')) # False
Common Pitfalls
- This only matches ASCII letters. For Unicode letters (accents, CJK, etc.), use \p{L} with the Unicode flag.
- Use * instead of + if you want to allow empty strings.
- Consider whether underscores should be included. \w matches [a-zA-Z0-9_].
Try It Yourself
Test this regex with our Regex Tester.
Frequently Asked Questions
How do I include underscores?
Add underscore to the character class: ^[a-zA-Z0-9_]+$. Alternatively, use \w which is equivalent to [a-zA-Z0-9_] in most regex engines. This is a common pattern for usernames and identifiers that allow underscores as word separators.
How do I match Unicode letters?
Use the Unicode property escape \p{L} (supported in JavaScript with the /u flag, Python, and Java). Example: /^[\p{L}0-9]+$/u matches letters from any language including accented characters, Cyrillic, CJK, Arabic, and more.
What is the difference between + and *?
+ requires one or more matches (non-empty string), while * allows zero or more matches (including empty string). For validation, + is usually correct because you want to reject empty inputs.