Reputation:
I have some html codes saved in a file. I want to replace all texts that match this pattern: @@[\w]{1,}@@
. but why this pattern in my java code doesn't work? is my pattern wrong?
String line = "\t<title>@@title@@</title>";
if(line.matches("@@title@@")) {
line = line.replaceAll("@@title@@", "Title");
}
Upvotes: 0
Views: 90
Reputation: 25874
In Java, String#matches only returns true if the whole string matches the regex. In your case you want this regex: .*@@title@@.*
.
I think String#contains is better for your case since you are not really want to match a regex but a substring.
Upvotes: 0
Reputation: 9609
line.matches("@@title@@")
means the whole line matches. Imagine it like this
line.matches("^@@title@@$")
And replaceAll
won't throw exception if there is no match, so you can simply drop your check:
String line = "\t<title>@@title@@</title>";
line = line.replaceAll("@@title@@", "Title");
Upvotes: 2