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 to use for testing correctly the regex?
thanks.
Java - String matches() Method This method tells whether or not this string matches the given regular expression. An invocation of this method of the form str. matches(regex) yields exactly the same result as the expression Pattern. matches(regex, str).
When you create a text question, along with word/character limits, you can validate for Regex pattern matching. To validate a field with a Regex pattern, click the Must match pattern check box.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With