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

后端 未结 8 1235
一向
一向 2020-11-27 02:44

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.

8条回答
  •  借酒劲吻你
    2020-11-27 03:14

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

提交回复
热议问题