You can check string is alphanumeric in Java using matches() method of Matcher class. The Matcher class is provided by java.util.regex package. Below I have shared a simple Java program in which I have taken a string and I am checking it using matches() method.
Java Program to Check String is Alphanumeric or not
java.util.regex.*; class AlphanumericExample { public static void main(String...s) { String s1="adA12", s2="jh@l"; System.out.println(s1.matches("[a-zA-Z0-9]+")); System.out.println(s2.matches("[a-zA-Z0-9]+")); } }
Output
In above example, I have used a pattern “[a-zA-Z0-9]+” inside matches() method. It means that the string can contains characters in between a to z, A to Z and 0 to 9. Here + means string can have one or more characters. matches() method returns true if the string is alphanumeric, otherwise it returns false.
Comment below if you are getting difficulty to understand anything.
How to Check String is Alphanumeric in Java?
It will be really helpful if you can elaborate the explanations and also help me with a code which takes input from the user and tells if its alphanumeric or not ? Thanks !
Thanks