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?
"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With