Difference in results between Java matches vs JavaScript match

Tags: , ,



I was brushing up on my regular expressions in java when I did a simple test

Pattern.matches("q", "Iraq"); //false
"Iraq".matches("q"); //false

But in JavaScript

/q/.test("Iraq"); //true
"Iraq".match("q"); //["q"] (which is truthy)

What is going on here? And can I make my java regex pattern “q” behave the same as JavaScript?

Answer

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");
}


Source: stackoverflow