<分区>
我对编程很陌生。我想检查字符串 s 是否包含 a-z 字符。我使用:
if(s.contains("a") || s.contains("b") || ... {
}
但是有什么方法可以用更短的代码来完成吗?非常感谢
<分区>
我对编程很陌生。我想检查字符串 s 是否包含 a-z 字符。我使用:
if(s.contains("a") || s.contains("b") || ... {
}
但是有什么方法可以用更短的代码来完成吗?非常感谢
最佳答案
你可以使用正则表达式
// 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
}
这将检查字符串是否包含至少一个字符 a-z
检查是否所有字符都是 a-z 使用:
if ( ! s.matches(".*[^a-z].*") ) {
// Do something
}
关于java正则表达式的更多信息
http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
关于java - 判断字符串是否包含 a-z 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24086968/