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).

Examples:

StringValidity
"abc123"Valid
"HelloWorld"Valid
"123456"Valid
"AbCdEfG"Valid
"aBc123"Valid
"a1b2c3"Valid
"Alphanumeric123"Valid
"Invalid String!"Invalid
"Spaces Are NotAllowed"Invalid
"Special@Characters"Invalid
"123_456"Invalid
""Valid


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(
                "abc123",
                "HelloWorld",
                "123456",
                "AbCdEfG",
                "aBc123",
                "a1b2c3",
                "Alphanumeric123",
                "Invalid String!",
                "Spaces Are NotAllowed",
                "Special@Characters",
                "123_456",
                ""
        );

        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: rakesh@code2care.org

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