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: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

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