Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 331
jermel Avatar asked Feb 19 '14 14:02

jermel


1 Answers

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");
}
like image 183
Pshemo Avatar answered Sep 28 '22 03:09

Pshemo