Testing regex with Java
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.
or
System.out.println(Pattern.compile("h{2}").matcher("hhh").find());
it returns true and not false as expected.
What's the problem? Maybe this is not the right statements 开发者_如何学Cto use for testing correctly the regex?
thanks.
The string hhh
contains two h
s, therefore the regex matches since the find()
method allows matching of substrings.
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:
"hhh".matches("h{2}")
will fail.
But this won't return true
.
System.out.println(Pattern.compile("^h{2,4}$").matcher("hhhhh").find());
^
is the beginning of the line
$
is the end of the line
You want to use .matches() and not .find(). You should also anchor it like @Tim said.
精彩评论