Bart van Heukelom
Bart van Heukelom

Reputation: 44084

Why does this regex not match?

I'm sure this type of question gets posted a lot here. I have this regex:

^\[.*\]

which should match

[Test]Hi there

And according to RegexPal, it does. However, in this Java SCCE it doesn't:

final String pat = "^\\[.*\\]";
final String str = "[Test]Hi there";
System.out.println(pat);
System.out.println(str);
System.out.println(str.matches(pat));

Output:

^\[.*\]
[Test]Hi there
false

Why doesn't it match?

Upvotes: 2

Views: 91

Answers (2)

instanceof me
instanceof me

Reputation: 39138

Because String#match will try to match your regex against the whole string. What you're looking for is Pattern.compile(pat).matcher(str).find(), see Matcher.

Upvotes: 1

Joachim Sauer
Joachim Sauer

Reputation: 308001

"match" in Java means "matches the whole string":

Attempts to match the entire region against the pattern.

Since your regex doesn't accept any characters after the last ] it will not "match" anything that has characters after the ].

You can use find to see if the string contains something that's matched by your regex (it will still have to be anchored at the beginning, since you use ^).

In other words ^\[.*\] will not match [Test]Hi there, but it will find [Test] within [Test]Hi there.

Upvotes: 10

Related Questions