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

て烟熏妆下的殇ゞ 提交于 2019-11-26 08:55:29

问题


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.


回答1:


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();



回答2:


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);



回答3:


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

Alternatively, you can use regex.




回答4:


Use this function to check if a string is alphanumeric:

public boolean isAlphanumeric(String str)
{
    char[] charArray = str.toCharArray();
    for(char c:charArray)
    {
        if (!Character.isLetterOrDigit(c))
            return false;
    }
    return true;
}

It saves having to import external libraries and the code can easily be modified should you later wish to perform different validation checks on strings.




回答5:


If you can use the Apache Commons library, then Commons-Lang StringUtils has a method called isAlphanumeric() that does what you're looking for.




回答6:


string.matches("^\\W*$"); should do what you want, but it does not include whitespace. string.matches("^(?:\\W|\\s)*$"); does match whitespace as well.




回答7:


You can use isLetter(char c) static method of Character class in Java.lang .

public boolean isAlpha(String s) {
    char[] charArr = s.toCharArray();

    for(char c : charArr) {
        if(!Character.isLetter(c)) {
            return false;
        }
    }
    return true;
}


来源:https://stackoverflow.com/questions/8248277/how-to-determine-if-a-string-has-non-alphanumeric-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!