Skip to content
Advertisement

Java regex Matcher.matches function does not match entire string

I am trying to match an entire string against a regex but the Matcher.match function returns true even when the entire string does not match.

JavaScript

You can see from the while loop that the regex matches only parts of the string “query1” , “query2” and “query3” but not the whole string. Yet, matcher.matches() returns true.

Where am I going wrong?

I checked the pattern on https://regex101.com/ as well and the entire string is not matched.

Advertisement

Answer

matches() method returns true because it needs a full string match. You say you tested the regular expression on regex101.com, but you forgot to add anchors to simulate matches() behavior.

See regex proof that your regex matches the whole string.

If you want to stop matching the entire string with this expression, do not use .*?, this pattern can match really a lot.

Use

JavaScript

Escaped version:

JavaScript

EXPLANATION

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement