Reputation: 12783
String url = "hello world";
String p = "world";
Pattern pattern = Pattern.compile(p);
Matcher matcher = pattern.matcher(url);
if (matcher.matches()) {
int start = matcher.start();
int end = matcher.end();
}
What am I doing wrong? How comes the if statement never gets hit?
Upvotes: 1
Views: 111
Reputation: 49567
You need to use find
because,
matches tries to match the patten against the entire string and implicitly add a ^ at the start and $ at the end of your pattern.
So your pattern is equivalent to "^world$".
Upvotes: 1
Reputation: 27180
Try to change your pattern to ".*world.*"
:
String p = ".*world.*";
That way it'll match any string that contains "world".
Upvotes: 0
Reputation: 21223
Try Matcher.find(). Matcher.matches()
checks whether the whole string matches the pattern.
Upvotes: 1
Reputation: 1628
I experienced same problem. I don't know the reason. If someone knows problem please post here. I had solved problem with using find() repeatedly instead of matches().
Upvotes: -1
Reputation: 3975
The matches()
method attempts to match the entire string to the pattern. You want the find()
method.
Upvotes: 4