Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 914
lugeno Avatar asked Nov 23 '11 19:11

lugeno


People also ask

How do you check if a character in a string is alphanumeric?

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 .

How do you check if a string contains a character or not?

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.

How do you find non-alphanumeric characters in Python?

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 .

What is non-alphanumeric characters examples?

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(').


2 Answers

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(); 
like image 81
Fabian Barney Avatar answered Sep 26 '22 06:09

Fabian Barney


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); 
like image 41
loscuropresagio Avatar answered Sep 25 '22 06:09

loscuropresagio