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?
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?
Share Improve this question edited Aug 28, 2020 at 19:40 Pshemo 124k25 gold badges191 silver badges275 bronze badges asked Feb 19, 2014 at 14:36 jermeljermel 2,33621 silver badges19 bronze badges 7 | Show 2 more comments3 Answers
Reset to default 6In 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.
Attempts to match the entire region against the pattern.
– Marko Topolnik Commented Feb 19, 2014 at 14:50