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

后端 未结 4 1383
别跟我提以往
别跟我提以往 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]
    
    0 讨论(0)
  • 2020-12-30 06:38
    if (string.matches("^[a-zA-Z0-9_]+$")) {
      // contains only listed chars
    } else {
      // contains other chars
    }
    
    0 讨论(0)
  • 2020-12-30 06:46

    For that particular class of String use the regular expression "\w+".

    Pattern p = Pattern.compile("\\w+");
    Matcher m = Pattern.matcher(str);
    
    if(m.matches()) {} 
    else {};
    

    Note that I use the Pattern object to compile the regex once so that it never has to be compiled again which may be nice if you are doing this check in a-lot or in a loop. As per the java docs...

    If a pattern is to be used multiple times, compiling it once and reusing it will be more efficient than invoking this method each time.

    0 讨论(0)
  • 2020-12-30 06:51

    Use a regular expression, like this one:

    ^[a-zA-Z0-9]+$
    

    http://regexlib.com/REDetails.aspx?regexp_id=1014

    0 讨论(0)
提交回复
热议问题