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("");
1
  • Turns out you don't need to quote }s. I guess it's the context lookup that's not working. Of course using Pattern.quote like in method one is still wrong. Commented Jan 2, 2018 at 1:35

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

The method 2 still needs to escape special characters }

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

Comments

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

1 Comment

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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.