Java 判断字符串是否包含 az 字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24086968/
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
Tell if string contains a-z chars
提问by
I very new to programming. I want to check if a string s contains a-z characters. I use:
我对编程很陌生。我想检查字符串 s 是否包含 az 字符。我用:
if(s.contains("a") || s.contains("b") || ... {
}
but is there any way for this to be done in shorter code? Thanks a lot
但是有什么办法可以用更短的代码来完成吗?非常感谢
采纳答案by mmohab
You can use regular expressions
您可以使用正则表达式
// to emulate contains, [a-z] will fail on more than one character,
// so you must add .* on both sides.
if (s.matches(".*[a-z].*")) {
// Do something
}
this will check if the string contains at least one character a-z
这将检查字符串是否至少包含一个字符 az
to check if all characters are a-z use:
检查是否所有字符都是 az 使用:
if ( ! s.matches(".*[^a-z].*") ) {
// Do something
}
for more information on regular expressions in java
有关 Java 中正则表达式的更多信息
http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
回答by Dan S
Use Regular Expressions. The Pattern.matches()method can do this easily. For example:
使用正则表达式。该Pattern.matches()方法可以很容易地做到这一点。例如:
Pattern.matches("[a-z]", "TESTING STRING a");
If you need to check a great number of string this class can be compiled internally to improve performance.
如果您需要检查大量字符串,可以在内部编译此类以提高性能。
回答by Giru Bhai
Try this
尝试这个
Pattern p = Pattern.compile("[a-z]");
if (p.matcher(stringToMatch).find()) {
//...
}
回答by Elliott Frisch
In addition to regular expressions, and assuming you actually want to know if the String doesn't contain only characters, you can use Character.isLetter(char)-
除了正则表达式,假设你真的想知道字符串是否只包含字符,你可以使用Character.isLetter(char)-
boolean hasNonLetters = false;
for (char ch : s.toCharArray()) {
if (!Character.isLetter(ch)) {
hasNonLetters = true;
break;
}
}
// hasNonLetters is true only if the String contains something that isn't a letter -
From the Javadoc for Character.isLetter(char)
,
从 Javadoc for Character.isLetter(char)
,
A character is considered to be a letter if its general category type, provided by
Character.getType(ch)
, is any of the following:UPPERCASE_LETTER LOWERCASE_LETTER TITLECASE_LETTER MODIFIER_LETTER OTHER_LETTER
一个字符被认为是一个字母,如果它的一般类别类型(由 提供
Character.getType(ch)
)是以下任何一种:UPPERCASE_LETTER LOWERCASE_LETTER TITLECASE_LETTER MODIFIER_LETTER OTHER_LETTER