Sudheej
Sudheej

Reputation: 2029

How to replace special character }} in a string with "" using regexp in java

I am trying to replace special character }} in a string with "" using regexp in Java, I tired the below two methods and it doesn't work. Please let me know what is wrong with these statements.

Note the string would also contain } which I would like to retain. Goal is to replace only }}.

Method 1:

    String buffer = obj.toJSONString() + ",";
    String result = buffer.replaceAll(Pattern.quote("(?<![\\w\\d])}}(?![\\w\\d])"), "");

Method 2:

Pattern.compile("(?<![\\w\\d])}}(?![\\w\\d])").matcher(buffer).replaceAll("");

Upvotes: 0

Views: 434

Answers (4)

Stephen C
Stephen C

Reputation: 719238

The quote in the following:

  String result = buffer.replaceAll(Pattern.quote("(?<![\\w\\d])}}(?![\\w\\d])"), "");

says to treat the regex as a literal string. That's wrong.

If you simply want to remove all }} irrespective of context:

  String result = buffer.replaceAll(Pattern.quote("}}"), "");

If you do need to respect the context, don't Pattern.quote(...) the regex!

The other problem is in the way that you attempt to specify the character classes. Since \d is a subset of \w, it is unnecessary to combine them. Just do this instead:

  String result = buffer.replaceAll("(?<!\\w)\\}\\}(?!\\w)"), "");

I'm not sure if it is strictly necessary to quote the } characters, but it is harmless if it is not necessary.

Upvotes: 3

Mahendra Kapadne
Mahendra Kapadne

Reputation: 426

Can you please try same with Apache StringUtils. It’s faster and should work in your case. Kindly find following links for reference.

  1. apache-stringutils-vs-java-implementation-of-replace

  2. Apache StringUtils 3.6

Upvotes: 0

Roman C
Roman C

Reputation: 1

The method 2 still needs to escape special characters }

Pattern.compile("(?<![\\w\\d])\\}\\}(?![\\w\\d])").matcher(buffer).replaceAll("");

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522007

Dont' use Pattern.quote, use a literal regex pattern, and escape the brackets:

Stringbuffer = obj.toJSONString() + ",";
String result = buffer.replaceAll("(?<![\\w\\d])\\}\\}(?![\\w\\d])", "");

Using Pattern.quote tells the regex engine to treat the string as literal. This does mean the brackets would not have to be escaped, but it would also render your lookarounds as literal text, probably not what you have in mind.

Upvotes: 1

Related Questions