Java Check if String is Alphanumeric using Regular Expression (RegEx)

A String is said to be alphanumeric if,

  • It contains lowercase alphabets from 'a' to 'z'.
  • It contains uppercase alphabets from 'A' to 'Z'.
  • It contains digits from '0' to '9'.
  • It does not contain any special characters, punctuation marks, or spaces.
  • The string may contain a combination of lowercase letters, uppercase letters, and digits in any order.
  • The length of the string can be any positive integer, including zero (empty string).


"Invalid String!"Invalid
"Spaces Are NotAllowed"Invalid

Now that we know what Alphanumerics are, let's take an example using Java RegEx.

package org.code2care.examples;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

public class AlphanumericRegExValidation {

    public static void main(String[] args) {

        List<String> strings = Arrays.asList(
                "Invalid String!",
                "Spaces Are NotAllowed",

        Pattern pattern = Pattern.compile("^[a-zA-Z0-9]+$");

        for (String str : strings) {
            boolean isValid = pattern.matcher(str).matches();
            System.out.println("String: " + str + " is Alphanumeric: " + isValid);
Result - Alphanumeric Regex Java

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap