How to check string is alphanumeric or not in Java


In this post we will learn how to check string is alphanumeric or not using regex (regular expression) and apache commons StringUtils class  in java.

Regular expressions provides one of the simplest ways to find whether string is alphanumeric or not in java.

Example >
string 'ab12' is alphanumeric
string '123' is alphanumeric
string 'abc' is alphanumeric


string '!#@' isn't alphanumeric
string 'abc@' isn't alphanumeric
string 'abc12#' isn't alphanumeric

Example 1 to check string is alphanumeric or not in java using regex >
regex (Regular Expression) used = "[a-zA-Z0-9]*"
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringAlphaNumericExample {
public static void main(String[] args) {
     Pattern pattern = Pattern.compile("[a-zA-Z0-9]*");
     String str = "abc12";
     Matcher matcher = pattern.matcher(str);
     if (matcher.matches()) {
          System.out.println("string '"+str + "' is alphanumeric");
     } else {
          System.out.println("string '"+str + "' isn't alphanumeric");
     }
}
}
/*
string 'abc12' is alphanumeric
*/



Example 2 to check string is alphanumeric or not in java using org.apache.commons.lang.StringUtils.isAlphanumeric(str) >
import org.apache.commons.lang.StringUtils;
public class StringContainsAlphaNumericExample2_UsingCommons {
public static void main(String[] args) {
     String str = "abc123";
     System.out.println(StringUtils.isAlphanumeric(str));
}
}
/*
true
*/

Jar used in above program = commons-lang.jar

No comments:

Post a Comment