0

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("");
Roman C
  • 49,761
  • 33
  • 66
  • 176
Sudheej
  • 1,873
  • 6
  • 30
  • 57
  • Turns out [you don't need to quote `}`s](http://www.regexplanet.com/share/index.html?share=yyyyyf01nnr). I guess it's the context lookup that's not working. Of course using `Pattern.quote` like in method one is still wrong. – xiaofeng.li Jan 02 '18 at 01:35

4 Answers4

3

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

The method 2 still needs to escape special characters }

Pattern.compile("(?<![\\w\\d])\\}\\}(?![\\w\\d])").matcher(buffer).replaceAll("");
Roman C
  • 49,761
  • 33
  • 66
  • 176
0

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

Mahendra Kapadne
  • 426
  • 1
  • 3
  • 10
  • 1) If the replacement needs to be context sensitive (as implied by the OP's regex!!) then StringUtils is not a solution. 2) Adding an extra dependency may be a concern. Especially, if performance isn't a significant issue. – Stephen C Jan 02 '18 at 01:50