Difference in results between Java matches vs JavaScript match

In JavaScript match returns substrings which matches used regex. In Java matches checks if entire string matches regex.

If you want to find substrings that match regex use Pattern and Matcher classes like

Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(yourData);
while(m.find()){
   m.group();//this will return current match in each iteration
   //you can also use other groups here using their indexes
   m.group(2);
   //or names (?<groupName>...)
   m.group("groupName");
}

This is because in Java Pattern#matches OR String#matches expects you to match complete input string not just a part of it.

On the other hand Javascript's String#match can match input partially as you're also seeing in your examples.


In JavaScript, String.match looks for a partial match. In Java, Pattern.matches returns true if the whole input string is matched by the given pattern. That is equivalent to say, in your example, that "iraq" should match ^q$, which it obvious doesn't.

Here it is from Java's Matcher Javadoc (note that Pattern.matches internally creates a Matcher then calls matches on it):

public boolean matches()

Attempts to match the entire region against the pattern. If the match succeeds then more information can be obtained via the start, end, and group methods.

Returns: true if, and only if, the entire region sequence matches this matcher's pattern

If you want to test for only a part of the string, add .*? at the beginning of the regex, and .* at the end, such as Pattern.match("iraq", ".*?q.*").

Note that .*q.* would also work, but using the reluctant operator in front might significantly improve performances if the input string is very long. See this answer for explanation on the difference between reluctant and greedy operators, and their effects on backtracking for explanation.