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

后端 未结 8 1237
一向
一向 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:06

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

提交回复
热议问题