Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing regex with Java

Tags:

java

regex

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.

like image 810
xdevel2000 Avatar asked Mar 17 '11 11:03

xdevel2000


People also ask

How do you check if a string matches a regex in Java?

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).

How do you validate a regex pattern?

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.


1 Answers

The string hhh contains two hs, 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.

like image 67
Tim Pietzcker Avatar answered Oct 11 '22 11:10

Tim Pietzcker