Check if a Java String is Numeric or Alphanumeric

We can make use of regular expressions to know if a string is numeric or alphanumeric in Java.

Let's take a look at some examples.

public class Example {

    public static void main(String[] args) {

        String string1 = "23.00"; // Numeric
        String string2 = "X01201A"; // Alphanumeric
        String string3 = "AXYKZ"; // Alphabetic

        System.out.println("String1 is " + (isNumeric(string1) ? "numeric" : "not numeric") + " and " +
                (isAlphaNumeric(string1) ? "alphanumeric" : "not alphanumeric"));

        System.out.println("String2 is " + (isNumeric(string2) ? "numeric" : "not numeric") + " and " +
                (isAlphaNumeric(string2) ? "alphanumeric" : "not alphanumeric"));

        System.out.println("String3 is " + (isNumeric(string3) ? "numeric" : "not numeric") + " and " +
                (isAlphaNumeric(string3) ? "alphanumeric" : "not alphanumeric"));
    }

    public static boolean isNumeric(String str) {
        return str.matches("-?\\d+(\\.\\d+)?");
    }

    public static boolean isAlphaNumeric(String str) {
        return str.matches("[a-zA-Z0-9]+");
    }
}
Output:

String1 is numeric and not alphanumeric
String2 is not numeric and alphanumeric
String3 is not numeric and alphanumeric

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!