Regex for Alphanumeric Characters in Java (With Examples)

The regex for alphanumeric characters is ^[a-zA-Z0-9]+$. Java examples for length limits, letter plus digit rules, spaces, Unicode letters and cleanup.

The regex ^[a-zA-Z0-9]+$ split into four parts with labels: ^ start of string, [a-zA-Z0-9] one letter or digit, + one or more times, $ end of string. Below, sample inputs: Lokesh123 and 2026 are accepted, Lokesh 123, user_1, an empty string and cafe with an accent are rejected.

The regex for alphanumeric characters is ^[a-zA-Z0-9]+$, which accepts a string made only of the letters A to Z (either case) and the digits 0 to 9. The square brackets list the allowed characters, + requires at least one of them, and ^ and $ make the rule apply to the whole string. Spaces, hyphens, the “_” character and accented letters are rejected.

We use the alphanumeric regex to validate user names, coupon codes, order references and file name parts, and to strip everything else from a string before we store or compare it.

The following example runs the main patterns of this article against sample strings, with the result of each line as a comment.

boolean valid = "abc123".matches("[a-zA-Z0-9]+");                          // true
boolean space = "abc 123".matches("[a-zA-Z0-9]+");                         // false
boolean empty = "".matches("[a-zA-Z0-9]+");                                // false
boolean length = "Lokesh".matches("[a-zA-Z0-9]{3,16}");                    // true

boolean both = "abc123".matches("(?=.*[a-zA-Z])(?=.*\\d)[a-zA-Z0-9]+");    // true
boolean noDigit = "abc".matches("(?=.*[a-zA-Z])(?=.*\\d)[a-zA-Z0-9]+");    // false

boolean accented = "caf\u00e9".matches("[a-zA-Z0-9]+");                    // false
boolean unicode = "caf\u00e9".matches("(?U)\\p{Alnum}+");                  // true

String cleaned = "Hello, World! 123".replaceAll("[^a-zA-Z0-9]", "");       // "HelloWorld123"

Notice that the empty string fails because of +, and that the accented “e” needs the Unicode version. The table sums up the variants that the rest of the article explains, from length limits and extra characters to letters in any language and a check without regex.

To allowRegexJava string literal
Letters and digits only^[a-zA-Z0-9]+$“^[a-zA-Z0-9]+$”
Letters and digits, 3 to 16 characters^[a-zA-Z0-9]{3,16}$“^[a-zA-Z0-9]{3,16}$”
At least one letter and one digit^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z0-9]+$“^(?=.*[a-zA-Z])(?=.*\\d)[a-zA-Z0-9]+$”
Letters and digits plus “_”^\w+$“^\\w+$”
Letters and digits in any language(?U)^\p{Alnum}+$“(?U)^\\p{Alnum}+$”

1. The Alphanumeric Regex Explained

Alphanumeric characters are letters and digits. In ASCII text, they are 26 lowercase letters, 26 uppercase letters and 10 digits, 62 characters in total. The pattern ^[a-zA-Z0-9]+$ has four parts.

The regex ^[a-zA-Z0-9]+$ split into four parts with labels: ^ start of string, [a-zA-Z0-9] one letter or digit, + one or more times, $ end of string. Below, sample inputs: Lokesh123 and 2026 are accepted, Lokesh 123, user_1, an empty string and cafe with an accent are rejected.
Each part of ^[a-zA-Z0-9]+$ adds one rule; a single character outside the class rejects the whole value
PartMeaning
^Start of the string
[a-zA-Z0-9]One character, which is a lowercase letter, an uppercase letter or a digit
+One or more of the previous character class
$End of the string

The ranges a-z, A-Z and 0-9 sit inside one character class, so their order does not matter, and [0-9A-Za-z] is the same set. The class matches one character; the + after it is what makes the pattern accept a whole word.

2. Validating Alphanumeric Input in Java

In Java, String.matches() is the shortest way to run the check. It returns true only when the regex matches the entire string, so the ^ and $ anchors are optional with it, as the start and end of line anchors article explains.

A sign-up service is the typical place for the check. It validates every user name on every request, so we compile the pattern once into a static final field and reject null before matching.

class UserNames {
    private static final Pattern ALPHANUMERIC = Pattern.compile("^[a-zA-Z0-9]+$");

    static boolean isValid(String name) {
        return name != null && ALPHANUMERIC.matcher(name).matches();
    }
}
boolean ok = UserNames.isValid("Lokesh123");          // true
boolean hyphen = UserNames.isValid("Lokesh123-");     // false
boolean missing = UserNames.isValid(null);            // false

The sample inputs in the table show what the pattern accepts and rejects.

InputResultReason
“Lokesh”trueLetters only
“Lokesh123”trueLetters and digits
“2026”trueDigits only
“Lokesh123-“falseHyphen
“Lokesh 123”falseSpace
“user_1”falseThe “_” character
“”falseEmpty string, and + needs one character
“cafe” with an accented “e”falseNon-ASCII letter

Since Java 11, Pattern.asMatchPredicate() turns a pattern into a Predicate<String> that checks the whole string. It fits stream filters and validation APIs that accept a predicate.

Predicate<String> isAlphanumeric = Pattern.compile("[a-zA-Z0-9]+").asMatchPredicate();

boolean accepted = isAlphanumeric.test("Lokesh123");     // true
boolean rejected = isAlphanumeric.test("Lokesh123-");    // false
List<String> codes = Stream.of("a1", "b-2", "c3").filter(isAlphanumeric).toList();   // [a1, c3]

For validation, we use matches() or anchors, never a plain find(). The method find() succeeds when any part of the input matches, so [a-zA-Z0-9]+ finds “Lokesh123” inside “Lokesh123-” and accepts it.

boolean wrong = Pattern.compile("[a-zA-Z0-9]+").matcher("Lokesh123-").find();     // true

3. Empty Strings and Length Limits

The quantifier decides whether an empty value passes and how long the value may be.

  • The quantifier * allows zero characters, so [a-zA-Z0-9]* accepts an empty string.
  • The quantifier + requires at least one character.
  • The quantifier {3,16} requires between 3 and 16 characters, a typical rule for user names.
boolean starEmpty = "".matches("[a-zA-Z0-9]*");                  // true
boolean plusEmpty = "".matches("[a-zA-Z0-9]+");                  // false

boolean tooShort = "ab".matches("[a-zA-Z0-9]{3,16}");            // false
boolean inRange = "Lokesh".matches("[a-zA-Z0-9]{3,16}");         // true
boolean tooLong = "a".repeat(17).matches("[a-zA-Z0-9]{3,16}");   // false

A length limit in the regex keeps the rule in one place. When the error message must say why the value failed, separate checks with String.length() give clearer messages. The article regex to validate min and max length of input covers length rules in detail.

4. Allowing Spaces, Hyphens and Other Extra Characters

Real input rules often allow one or two more characters. We add them to the character class.

To allowRegexNote
Letters, digits and “_”^\w+$ or ^[a-zA-Z0-9_]+$\w is the same set as the class
Letters, digits, “_” and “-“^[a-zA-Z0-9_-]+$A hyphen at the end of the class is literal
Letters, digits and spaces^[a-zA-Z0-9 ]+$A literal space only
Lowercase letters and digits^[a-z0-9]+$Rejects uppercase
Letters and digits, case-insensitive(?i)^[a-z0-9]+$Same result as [a-zA-Z0-9]
boolean underscore = "user_1".matches("\\w+");                  // true
boolean dash = "user-1".matches("[a-zA-Z0-9_-]+");              // true
boolean spaces = "abc 123".matches("[a-zA-Z0-9 ]+");            // true
boolean tab = "abc\t123".matches("[a-zA-Z0-9 ]+");              // false
boolean anyWhitespace = "abc\t123".matches("[a-zA-Z0-9\\s]+");  // true
boolean upper = "Abc123".matches("[a-z0-9]+");                  // false
boolean ignoreCase = "ABC123".matches("(?i)[a-z0-9]+");         // true

To allow spaces, we write a literal space in the class, not \s. The class \s also accepts tabs and line breaks, which are rarely wanted in a name or a code.

5. Requiring at Least One Letter and One Digit

Some rules, such as product codes or simple passwords, need both kinds of characters. A lookahead checks a condition without consuming text, so we place one lookahead per condition at the start of the pattern.

PartMeaning
(?=.*[a-zA-Z])Somewhere ahead there is a letter
(?=.*\d)Somewhere ahead there is a digit
[a-zA-Z0-9]+The whole string contains only letters and digits
String letterAndDigit = "^(?=.*[a-zA-Z])(?=.*\\d)[a-zA-Z0-9]+$";

boolean mixed = "abc123".matches(letterAndDigit);       // true
boolean lettersOnly = "abc".matches(letterAndDigit);    // false
boolean digitsOnly = "123".matches(letterAndDigit);     // false
boolean bang = "abc123!".matches(letterAndDigit);       // false

The same technique extends to stricter password rules, which the regex password validator builds on.

6. Letters and Digits in Any Language

The class [a-zA-Z0-9] is ASCII-only, so it rejects names such as “cafe” written with an accented “e”. In Java, \p{Alnum} is also ASCII-only by default, despite its name, because it is the POSIX class [a-zA-Z0-9]. The UNICODE_CHARACTER_CLASS flag, written inline as (?U), switches \p{Alnum}, \w and \d to their Unicode definitions.

boolean posix = "\u00e9".matches("\\p{Alnum}");              // false
boolean unicodeAlnum = "\u00e9".matches("(?U)\\p{Alnum}");    // true
boolean arabicDigit = "\u0663".matches("\\d");                // false
boolean arabicAlnum = "\u0663".matches("(?U)\\p{Alnum}");     // true

boolean half = "\u00bd".matches("(?U)\\p{Alnum}");            // false
boolean halfNumber = "\u00bd".matches("[\\p{L}\\p{N}]");      // true
boolean decimalOnly = "\u00e9".matches("[\\p{L}\\p{Nd}]");    // true

The character U+00E9 is “e” with an acute accent, U+0663 is the Arabic-Indic digit three, and U+00BD is the fraction one half. There are two common Unicode choices, and they differ in what counts as a number.

  • The pattern (?U)\p{Alnum} accepts alphabetic characters and decimal digits in any script.
  • The class [\p{L}\p{N}] accepts any letter (\p{L}) and any number (\p{N}), which also includes symbols such as the fraction one half and superscript two. The class [\p{L}\p{Nd}] limits numbers to decimal digits.

For names and user input in several languages, (?U)^\p{Alnum}+$ is a good default.

7. Removing Non-Alphanumeric Characters

To clean a string instead of rejecting it, we negate the class with a caret and replace every match with an empty string. Replacing runs of other characters with a hyphen produces a URL-friendly value, such as the slug of a blog post.

String compact = "Hello, World! 123".replaceAll("[^a-zA-Z0-9]", "");    // "HelloWorld123"
String slug = "a-b_c d".replaceAll("[^a-zA-Z0-9]+", "-");              // "a-b-c-d"

For text that contains control characters or non-printable bytes, the article remove non-ASCII and non-printable characters shows the matching character classes.

8. Checking Without a Regex

The method Character.isLetterOrDigit() checks one character against the Unicode rules, and String.chars() streams the characters of a string. Together they give a regex-free check.

boolean plain = "Lokesh123".chars().allMatch(Character::isLetterOrDigit);       // true
boolean accent = "caf\u00e9".chars().allMatch(Character::isLetterOrDigit);      // true
boolean blank = "".chars().allMatch(Character::isLetterOrDigit);                // true

The stream check returns true for an empty string, so we add an isEmpty() test when a value is required. It also accepts non-ASCII letters. When only ASCII is allowed, the regex ^[a-zA-Z0-9]+$ is the simpler rule.

Projects that already use Apache Commons Lang can call StringUtils.isAlphanumeric(). It follows the Unicode rules like Character.isLetterOrDigit(), and it returns false for null and for an empty string.

boolean commons = StringUtils.isAlphanumeric("Lokesh123");    // true
boolean commonsEmpty = StringUtils.isAlphanumeric("");        // false

9. Trying the Checks Yourself

The alphanumeric project on GitHub prints every check from this article with its result. Its JUnit 6 tests assert the valid and invalid samples, the variants and the Unicode cases. It needs Java 25 and Maven.

mvn -q compile exec:java
mvn test

10. Regex for Alphanumeric Characters FAQs

The \w shortcut, the opposite class, spaces between words and letter case cause most follow-up questions about the alphanumeric regex. Every other pattern topic is linked from the Java regex tutorial.

10.1. Does \w Match the “_” Character?

Yes. In Java, \w is [a-zA-Z_0-9], so “user_1” passes \w+ but fails [a-zA-Z0-9]+. When “_” is not allowed, we write the class out in full.

10.2. What Is the Regex for Non-Alphanumeric Characters?

The negated class [^a-zA-Z0-9] matches one character that is not an ASCII letter or digit. The shorter \W is the opposite of \w, so it does not match the “_” character.

boolean notAlnum = "_".matches("[^a-zA-Z0-9]");    // true
boolean notWord = "_".matches("\\W");              // false

10.3. How Do I Allow Single Spaces Between Words Only?

We repeat a group that starts with one space, as in ^[a-zA-Z0-9]+( [a-zA-Z0-9]+)*$. The pattern rejects leading spaces, trailing spaces and double spaces, which a class with a space inside cannot do.

String words = "^[a-zA-Z0-9]+( [a-zA-Z0-9]+)*$";
boolean single = "Order 42 ready".matches(words);    // true
boolean leading = " Order 42".matches(words);        // false
boolean twoSpaces = "Order  42".matches(words);      // false

10.4. Is the Alphanumeric Regex Case-Sensitive?

Yes. The class [a-z0-9] rejects “A”. Both ranges in [a-zA-Z0-9] or the (?i) flag accept either case, as section 4 shows.

11. Conclusion

The regex ^[a-zA-Z0-9]+$ checks for an ASCII alphanumeric string, and in Java we run it with matches() or with a compiled Pattern. We change the quantifier for length rules, add characters to the class for variants such as “_” or a space, and add lookaheads when a letter and a digit are both required.

For input in other languages, (?U)^\p{Alnum}+$ accepts letters and digits from any script, because plain \p{Alnum} is ASCII-only in Java.

12. References

Happy Learning !!

Source Code on Github

Leave a Comment

  1. But that regular expression won’t work for languages using a different script such as Cyrillic. How do you make a regular expression recognize alphanumeric character in any Java Locale supported language?

    • String regex = “\\p{Alnum}+”;

      This is a Unicode property that matches any alphanumeric character (letters and digits) recognized in any Java Locale.

Comments are closed.

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.