如何检查选择的字符是否只在字符串中?

Jos*_*eph 12 java string character

检查字符串是否仅包含以下字符的最佳和最简单方法是什么:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_
Run Code Online (Sandbox Code Playgroud)

我想要一个像这样的伪代码的例子:

//If String contains other characters
else
//if string contains only those letters
Run Code Online (Sandbox Code Playgroud)

请和谢谢:)

Pab*_*oni 25

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


And*_*ite 6

对于该特定类别的字符串,请使用正则表达式“\w+”。

Pattern p = Pattern.compile("\\w+");
Matcher m = Pattern.matcher(str);

if(m.matches()) {} 
else {};
Run Code Online (Sandbox Code Playgroud)

请注意,我使用 Pattern 对象来编译正则表达式一次,这样就不必再次编译它,如果您在大量或循环中进行此检查,这可能会很好。根据java文档...

如果要多次使用某个模式,则编译一次并重用它会比每次调用此方法更有效。