用 Java 测试正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5338399/
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
Testing regex with Java
提问by xdevel2000
I'm learning regex and I'm using the following code snippet for testing purpose:
我正在学习正则表达式,并且正在使用以下代码片段进行测试:
String regex = "";
String test = "";
Pattern.compile(regex).matcher(test).find();
but when I try some like this:
但是当我尝试这样的时候:
System.out.println(Pattern.compile("h{2,4}").matcher("hhhhh").find());
it returns true and not false as expected.
它按预期返回 true 而不是 false。
or
或者
System.out.println(Pattern.compile("h{2}").matcher("hhh").find());
it returns true and not false as expected.
它按预期返回 true 而不是 false。
What's the problem? Maybe this is not the right statements to use for testing correctly the regex?
有什么问题?也许这不是用于正确测试正则表达式的正确语句?
thanks.
谢谢。
回答by Tim Pietzcker
The string hhh
contains two h
s, therefore the regex matches since the find()
method allows matching of substrings.
该字符串hhh
包含两个h
s,因此正则表达式匹配,因为该find()
方法允许匹配子字符串。
If you anchor the regex to force it to match the entire string, the regex will fail:
如果您锚定正则表达式以强制它匹配整个字符串,则正则表达式将失败:
^h{2}$
Another possibility would be to use the matches()
method:
另一种可能性是使用该matches()
方法:
"hhh".matches("h{2}")
will fail.
将失败。
回答by adarshr
But this won't return true
.
但这不会回来true
。
System.out.println(Pattern.compile("^h{2,4}$").matcher("hhhhh").find());
^
is the beginning of the line
^
是行的开头
$
is the end of the line
$
是行尾
回答by Adam Gent
You want to use .matches()and not .find(). You should also anchor it like @Tim said.
您想使用.matches()而不是 .find()。你也应该像@Tim 所说的那样锚定它。