user63898
user63898

Reputation: 30915

Java replace curly brackets string using replaceAll when the value is in variable, java 8

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?

Upvotes: 0

Views: 1072

Answers (1)

Lino
Lino

Reputation: 19926

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

Upvotes: 4

Related Questions