I need a method that can tell me if a String has non alphanumeric characters.
For example if the String is "abcdef?" or "abcdefà", the method must return true.
Python string isalnum() function returns True if it's made of alphanumeric characters only. A character is alphanumeric if it's either an alpha or a number. If the string is empty, then isalnum() returns False .
You can use string. indexOf('a') . If the char a is present in string : it returns the the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.
isalnum() is a built-in Python function that checks whether all characters in a string are alphanumeric. In other words, isalnum() checks whether a string contains only letters or numbers or both. If all characters are alphanumeric, isalnum() returns the value True ; otherwise, the method returns the value False .
Non-alphanumeric characters comprise of all the characters except alphabets and numbers. It can be punctuation characters like exclamation mark(!), at symbol(@), commas(, ), question mark(?), colon(:), dash(-) etc and special characters like dollar sign($), equal symbol(=), plus sign(+), apostrophes(').
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With