Validation
Alphanumeric Only Regex
Codes, reference numbers and simple identifiers are often restricted to letters and digits. This pattern accepts one or more characters from A to Z in either case and 0 to 9, anchored at both ends so that a single space, dash or symbol anywhere makes the whole input fail. The plus quantifier also rejects an empty string, so a blank form field does not pass. Because the classes are ASCII, accented letters and letters from other alphabets are rejected too, which is usually what you want for machine-readable codes but not for names typed by people.
Pattern (JavaScript)
/^[A-Za-z0-9]+$/Starts at the start of the line/string, then a letter or digit, one or more times, then the end of the line/string.
Examples
Matches
- ✓ abc123
- ✓ ABC
- ✓ 2026
Does not match
- ✗ abc 123
- ✗ abc-123
- ✗
Try it
0 matches (JavaScript engine)
abc123
ABC
2026
abc 123
abc-123
Code in 8 languages
Converted automatically from the JavaScript pattern; language-specific notes are shown where the syntax or support differs.
JavaScript
const re = /^[A-Za-z0-9]+$/g;
const text = "abc123";
const matches = [...text.matchAll(re)].map((m) => m[0]);
console.log(matches);Python
import re
pattern = re.compile(r'^[A-Za-z0-9]+$')
text = 'abc123'
matches = [m.group(0) for m in pattern.finditer(text)]
print(matches)PHP
<?php
$pattern = '/^[A-Za-z0-9]+$/';
$text = 'abc123';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("^[A-Za-z0-9]+$");
String text = "abc123";
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}Go
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`^[A-Za-z0-9]+$`)
text := "abc123"
fmt.Println(re.FindAllString(text, -1))
}C#
using System;
using System.Text.RegularExpressions;
var pattern = new Regex(@"^[A-Za-z0-9]+$");
var text = "abc123";
foreach (Match m in pattern.Matches(text))
{
Console.WriteLine(m.Value);
}Rust
// Cargo.toml: regex = "1"
use regex::Regex;
fn main() {
let re = Regex::new(r"^[A-Za-z0-9]+$").unwrap();
let text = "abc123";
for m in re.find_iter(text) {
println!("{}", m.as_str());
}
}- Add regex = "1" under [dependencies] in Cargo.toml.
Ruby
pattern = /^[A-Za-z0-9]+$/
text = 'abc123'
matches = text.to_enum(:scan, pattern).map { Regexp.last_match[0] }
p matchesFrequently asked questions
- Why not use \w+ instead?
- \w also matches the underscore. If underscores should be rejected, the explicit class [A-Za-z0-9] is the precise choice.
- How do I accept letters from other alphabets?
- With the u flag, use ^[\p{L}\p{N}]+$. That accepts any Unicode letter or number, not just ASCII.
- Does it reject an empty input?
- Yes. The plus quantifier needs at least one character. Use a star instead if empty input should be allowed.