Java 当值在变量中时,使用 replaceAll 替换大括号字符串,java 8
Java replace curly brackets string using replaceAll when the value is in variable, java 8
我有一个变量:
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 = {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
但如果我这样做:
content = content.replaceAll(source,"\$\{VAR\}");
一切正常。我如何模仿或修复 replaceAll?
来自 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;
强调 可能 ,这可能会失败,具体取决于您的 Java 版本(尽管我无法通过 Java 8、11、 12、15 and even the early access Java 16)
您可以使用 Matcher.quoteReplacement(String)
转义替换字符串中的 \ 和 $ 字符,如稍后在 javadoc 中所述:
Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.
因此将您的代码更改为(假设您要将内容替换为 ${VAR}
而不是 ${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);
这导致:
<xxx.xx.name>${VAR}</xxx.xx.name>
DEMO
我有一个变量:
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 = {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
但如果我这样做:
content = content.replaceAll(source,"\$\{VAR\}");
一切正常。我如何模仿或修复 replaceAll?
来自 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;
强调 可能 ,这可能会失败,具体取决于您的 Java 版本(尽管我无法通过 Java 8、11、 12、15 and even the early access Java 16)
您可以使用 Matcher.quoteReplacement(String)
转义替换字符串中的 \ 和 $ 字符,如稍后在 javadoc 中所述:
Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.
因此将您的代码更改为(假设您要将内容替换为 ${VAR}
而不是 ${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);
这导致:
<xxx.xx.name>${VAR}</xxx.xx.name>