Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java正则表达式中转义美元和大括号(即${title})?_Java_Regex - Fatal编程技术网

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

如何在java正则表达式中转义美元和大括号(即${title})?,java,regex,Java,Regex,你是怎么做到的 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)

你是怎么做到的

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);

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

\$\{title\}

模式类有一个转义函数用于类似的用途

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

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

在正则表达式中,转义字符是
\
要使用它,我们必须编写
\
作为
字符串
,将
\
用作转义字符

例如
str=str.replaceAll(“rot\\\*速度”、“转子速度”)

rot*速度
将替换为
转子速度

.

我没有加载模板语言来替换一个简单字符串。谢谢你的提示。反斜杠将由Java而不是正则表达式转义。然后转义反斜杠:
\\\$\\{title\\}
+1,用于在regexp中显示相对未知的转义序列