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.