How to determine if a String has non-alphanumeric characters? How to determine if a String has non-alphanumeric characters? java java

How to determine if a String has non-alphanumeric characters?


Using Apache Commons Lang:

!StringUtils.isAlphanumeric(String)

Alternativly iterate over String's characters and check with:

!Character.isLetterOrDigit(char)

You've still one problem left:Your example string "abcdefà" is alphanumeric, since à is a letter. But I think you want it to be considered non-alphanumeric, right?!

So you may want to use regular expression instead:

String s = "abcdefà";Pattern p = Pattern.compile("[^a-zA-Z0-9]");boolean hasSpecialChar = p.matcher(s).find();


One approach is to do that using the String class itself.Let's say that your string is something like that:

String s = "some text";boolean hasNonAlpha = s.matches("^.*[^a-zA-Z0-9 ].*$");

one other is to use an external library, such as Apache commons:

String s = "some text";boolean hasNonAlpha = !StringUtils.isAlphanumeric(s);


You have to go through each character in the String and check Character.isDigit(char); or Character.isletter(char);

Alternatively, you can use regex.