Java 如何检查字符串中是否只有选定的字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4433998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if only chosen characters are in a string?
提问by Joseph
What's the best and easiest way to check if a string only contains the following characters:
检查字符串是否仅包含以下字符的最佳和最简单的方法是什么:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_
I want like an example like this pseudo-code:
我想要像这样的伪代码示例:
//If String contains other characters
else
//if string contains only those letters
Please and thanks :)
请和谢谢:)
采纳答案by Pablo Lalloni
if (string.matches("^[a-zA-Z0-9_]+$")) {
// contains only listed chars
} else {
// contains other chars
}
回答by Andrew White
For that particular class of String use the regular expression "\w+".
对于该特定类的字符串,请使用正则表达式“\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 onceso 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...
请注意,我使用 Pattern 对象编译正则表达式一次,以便它永远不必再次编译,如果您在大量或循环中进行此检查,这可能会很好。根据java文档...
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.
如果一个模式要被多次使用,编译一次并重用它会比每次调用这个方法更有效率。
回答by Robert Harvey
Use a regular expression, like this one:
使用正则表达式,如下所示:
^[a-zA-Z0-9]+$
回答by gertas
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:
根据 JavaDoc for Pattern:
\w A word character: [a-zA-Z_0-9]
\W A non-word character: [^\w]