How to check if only chosen characters are in a string?

后端 未结 4 1384
别跟我提以往
别跟我提以往 2020-12-30 06:19

What\'s the best and easiest way to check if a string only contains the following characters:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_         


        
4条回答
  •  生来不讨喜
    2020-12-30 06:36

    My turn:

    static final Pattern bad = Pattern.compile("\\W|^$");
    //...
    if (bad.matcher(suspect).find()) {
      // String contains other characters
    } else {
      // string contains only those letters
    }
    

    Above searches for single not matching or empty string.

    And according to JavaDoc for Pattern:

    \w  A word character: [a-zA-Z_0-9]
    \W  A non-word character: [^\w]
    

提交回复
热议问题