我需要澄清“缺少要转义的字符”异常

Lor*_*ore 1 java string

我有以下代码:

public class Test {

public static void main(String[] args) {
    String path = "${file.path}/fld/";
    String realValue = "C:\\path\\smtg\\";
    String variable = "${file.path}";
    path = path.replaceAll("\\$\\{" + variable.substring(2, variable.length() - 1) + "\\}", realValue);
    System.out.println(path);
    }
}
Run Code Online (Sandbox Code Playgroud)

这给了我以下例外:

Exception in thread "main" java.lang.IllegalArgumentException: character to be escaped is missing
at java.util.regex.Matcher.appendReplacement(Matcher.java:809)
at java.util.regex.Matcher.replaceAll(Matcher.java:955)
at java.lang.String.replaceAll(String.java:2223)
at testCode.Test.main(Test.java:9)
Run Code Online (Sandbox Code Playgroud)

我已经找到了有关此问题的一些问题,但仍然不了解此错误。有人可以解释我发生了什么吗?

我知道这样做replace会很好,但是很遗憾,我的同事们不想修改此代码。因此,我需要知道提供解决方案的确切问题,因为在其他安装中它可以工作。

Ves*_*dov 5

对于您的特殊情况,您需要执行以下操作:

public static void main(String[] args) {
    String path = "${file.path}/fld/";
    String realValue = "C:\\\\path\\\\smtg\\\\";  //Notice the double slashes here
    String variable = "${file.path}";
    path = path.replaceAll("\\$\\{" + variable.substring(2, variable.length() - 1) + "\\}", realValue);
    System.out.println(path);
}
Run Code Online (Sandbox Code Playgroud)

现在进行解释。当您执行操作时replaceAll,字符串的第二部分也将由Java解释,并具有特殊字符,如\$。因此,为了在字符串中添加\,您需要对其进行转义,并且变成\,\\如果您想在结果字符串文字中使用它,则需要对其中的每一个进行转义,以使其成为"\\\\"

如果您在匹配器中检查replaceAll方法上的Java文档:https : //docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#replaceAll%28java.lang.String%29

请注意,替换字符串中的反斜杠(\)和美元符号($)可能导致结果与被当作文字替换字符串的结果有所不同。如上所述,美元符号可被视为对捕获的子序列的引用,并且反斜杠用于转义替换字符串中的文字字符。

在您的情况下,一种更简单的解决方案是使用,replace而不是replaceAll因为您的模式非常简单并且不需要正则表达式支持,您可以将其与完整字符串“ $ {file.path}”进行匹配

path = path.replace("${file.path}", realValue);
//or even
path = path.replace(variable, realValue);
Run Code Online (Sandbox Code Playgroud)