user123321
user123321

Reputation: 12783

Silly RegEx issue. What am I doing wrong?

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

Answers (5)

RanRag
RanRag

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

zw324
zw324

Reputation: 27180

Try to change your pattern to ".*world.*":

String p = ".*world.*";

That way it'll match any string that contains "world".

Upvotes: 0

tenorsax
tenorsax

Reputation: 21223

Try Matcher.find(). Matcher.matches() checks whether the whole string matches the pattern.

Upvotes: 1

lulumeya
lulumeya

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

jcopenha
jcopenha

Reputation: 3975

The matches() method attempts to match the entire string to the pattern. You want the find() method.

Upvotes: 4

Related Questions