开发者

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

开发者 https://www.devze.com 2023-01-30 04:21 出处:网络
What\'s the best and easiest way to check if a string only contains the following characters: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_

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

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_
开发者_StackOverflow社区

I want like an example like this pseudo-code:

//If String contains other characters
else
//if string contains only those letters

Please and thanks :)


if (string.matches("^[a-zA-Z0-9_]+$")) {
  // contains only listed chars
} else {
  // contains other chars
}


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消