0

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");
}
1
  • Counsel: do not parse HTML with regexes. Use HTML parsers. Commented Jul 4, 2013 at 9:02

2 Answers 2

2
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");
Sign up to request clarification or add additional context in comments.

2 Comments

how to prevent it from comparing the pattern with whole line?
@user88731 Use java.util.regex package.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.