java java的String.matches方法的正则表达式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4405114/
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
Regex for java's String.matches method?
提问by sMaN
Basically my question is this, why is:
基本上我的问题是这样的,为什么是:
String word = "unauthenticated";
word.matches("[a-z]");
returning false? (Developed in java1.6)
返回假?(java1.6开发)
Basically I want to see if a string passed to me has alpha chars in it.
基本上我想看看传递给我的字符串是否包含 alpha 字符。
回答by Greg Hewgill
The String.matches()
function matches your regular expression against the wholestring (as if your regex had ^
at the start and $
at the end). If you want to search for a regular expression somewhere within a string, use Matcher.find()
.
该String.matches()
函数将您的正则表达式与整个字符串匹配(就像您的正则表达式^
在开头和$
结尾都有)。如果要搜索字符串中某处的正则表达式,请使用Matcher.find()
.
The correct method depends on what you want to do:
正确的方法取决于你想做什么:
- Check to see whether your input string consists entirelyof alphabetic characters (
String.matches()
with[a-z]+
) - Check to see whether your input string contains anyalphabetic character (and perhaps some others) (
Matcher.find()
with[a-z]
)
- 检查您的输入字符串是否完全由字母字符组成(
String.matches()
with[a-z]+
) - 检查您的输入字符串是否包含任何字母字符(可能还有其他一些字符)(
Matcher.find()
带有[a-z]
)
回答by jjnguy
Your code is checking to see if the word matches one character. What you want to check is if the word matches any number of alphabetic characters like the following:
您的代码正在检查单词是否与一个字符匹配。您要检查的是该单词是否与任意数量的字母字符匹配,如下所示:
word.matches("[a-z]+");
回答by Kissaki
with [a-z]
you math for ONE character.
和[a-z]
你一起计算一个字符。
What you're probably looking for is [a-z]*
您可能正在寻找的是 [a-z]*