Skip to content
Advertisement

Difference in results between Java matches vs JavaScript match

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?

Advertisement

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");
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement