你如何在java正则表达式中逃避美元和大括号(即$ {title})?

即你怎么做?

String string = "Sample string with ${title} to be inserted."; string.replaceAll("${title}", title); 

以下所有结果都会导致错误:

 string.replaceAll("\\${title}", title); string.replaceAll("\\\\${title}", title); string.replaceAll("\\\\$\\{title\\}", title); 

而且,似乎没有任何工作,这一切都会导致如下错误:

 java.util.regex.PatternSyntaxException: Illegal repetition near index 4 \\$\\{title\\} at java.util.regex.Pattern.error(Pattern.java:1713) at java.util.regex.Pattern.closure(Pattern.java:2775) at java.util.regex.Pattern.sequence(Pattern.java:1889) at java.util.regex.Pattern.expr(Pattern.java:1752) 

不确定最后一个会导致错误; 它只是不匹配任何东西,因为你在$上使用了太多的反斜杠。

这应该工作:

 string.replaceAll("\\$\\{title\\}", title); 

Pattern类有一个转义函数,用于这样的用途

 string.replaceAll(Pattern.quote("${title}"), title); 

您可以将搜索字符串转义为\Q${title}\E

这听起来像是FreeMarker等模板语言的典型用例。

\$\{title\}

在正则表达式中,转义字符是\来使用它我们必须在String\\\用作转义字符。

例如str = str.replaceAll("rot\\*speed", "rotorspeed");

rot*speed将被rotorspeed取代。