Testing regex using Java

I am learning regex, and for testing purposes, I use the following code snippet:

String regex = "";
String test = "";
Pattern.compile(regex).matcher(test).find();

but when I try something like this:

System.out.println(Pattern.compile("h{2,4}").matcher("hhhhh").find()); 

it returns true, not false as expected.

or

System.out.println(Pattern.compile("h{2}").matcher("hhh").find());

it returns true, not false as expected.

What is the problem? Maybe these are incorrect statements for the correct validation of the regular expression?

thank.

+3
source share
3 answers

The string hhhcontains two hs, so the regular expression is the same as the method find()allows matching substrings.

If you bind a regular expression to make it match the entire string, the regular expression will not execute:

^h{2}$

Another possibility is to use the method matches():

"hhh".matches("h{2}")

will fail.

+7

true.

System.out.println(Pattern.compile("^h{2,4}$").matcher("hhhhh").find()); 

^ -

$ -

0

You want to use . matches () , not .find (). You should also bind it as @Tim said.

0
source

All Articles