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

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

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_ 

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

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

请和谢谢:)

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

对于该特定String类,请使用正则表达式“\ w +”。

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

请注意,我使用Pattern对象编译一次正则表达式以便它永远不必再次编译,如果您在一个批次或循环中进行此检查可能会很好。 根据java文档…

如果要多次使用模式,则对其进行一次编译并重新使用它将比每次调用此方法更有效。

使用正则表达式,如下所示:

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

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

轮到我了:

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

上面搜索单个不匹配或空字符串。

根据JavaDoc for Pattern :

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