0

I have a variable:

String content = "<xxx.xx.name>xxx.xxx.com:111</xxx.xx.name>";
String destination = "\\$\\{VAR\\}";
String source = "xxx.xxx.com:111";
content = content.replaceAll(source, destination);

Result:

result = {IllegalArgumentException@781} Method threw 'java.lang.IllegalArgumentException' exception.
detailMessage = "Illegal group reference"
cause = {IllegalArgumentException@781} "java.lang.IllegalArgumentException: Illegal group reference"
stackTrace = {StackTraceElement[5]@783} 
suppressedExceptions = {Collections$UnmodifiableRandomAccessList@773}  size = 0

But if I do:

content = content.replaceAll(source,"\\$\\{VAR\\}");

all is working fine. How can I mimic or fix the replaceAll?

2
  • 1
    Both work fine for me; can't reproduce the issue. (Java 11.0.6) Commented Sep 30, 2020 at 20:25
  • java 8 is what im working with Commented Oct 1, 2020 at 4:41

1 Answer 1

4

From the documentation of String.replaceAll(String, String):

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string;

Emphasis on the may, depending on your Java version this may fail (though I fail to reproduce your problem with Java 8, 11, 12, 15 and even the early access Java 16)

You can use Matcher.quoteReplacement(String) to escape your \ and $ chars in the replacement string, as described later on in the javadoc:

Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

So change your code to this (assuming you want to replace the contents with ${VAR} and not with \${VAR\}):

String content = "<xxx.xx.name>xxx.xxx.com:111</xxx.xx.name>";
String destination = Matcher.quoteReplacement("${VAR}");
String source = "xxx.xxx.com:111";
content = content.replaceAll(source, destination);

Which results in:

<xxx.xx.name>${VAR}</xxx.xx.name>

DEMO

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

4 Comments

Do you have an idea why apparently only Java 15 "fails" here?
@akuzminykh ernest_k commented this, but since then have removed their comment, I checked with the latest build from Java 15 and was not able to reproduce this problem.
Yeah, I also got curious after the comment about Java 15 working. I think it's not likely that a basic method like String#replaceAll breaks because of a new Java version. If that's the case, I think it's interesting why.
@akuzminykh I guess, it’s not replaceAll but the processing of the string literals that changed as a side effect of adding that text blocks feature.

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.