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:
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!