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

时间:2021-09-14 00:18:11

Ie how do you do this?

即你怎么做?

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

All of the following results in an error:

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

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

And more, nothing seems to work, it all results in an error like this:

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

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)

6 个解决方案

#1


14  

Not sure how the last one would result in an error; it'd just not match anything because you're using too many backslashes on the $.

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

This should work:

这应该工作:

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

#2


23  

the Pattern class has a escape function for uses like this

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

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

#3


6  

You could escape the search string as \Q${title}\E

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

#4


1  

This sounds like a typical use case of template language such as FreeMarker.

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

#5


0  

\$\{title\}

\ $ \ {标题\}

#6


0  

In Regular Expression the escape character is \ to use this we have to write \\ as in String, \ is use as escape character.

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

For example str = str.replaceAll("rot\\*speed", "rotorspeed");

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

rot*speed will be replace with rotorspeed .

rot * speed将被rotorspeed取代。

#1


14  

Not sure how the last one would result in an error; it'd just not match anything because you're using too many backslashes on the $.

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

This should work:

这应该工作:

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

#2


23  

the Pattern class has a escape function for uses like this

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

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

#3


6  

You could escape the search string as \Q${title}\E

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

#4


1  

This sounds like a typical use case of template language such as FreeMarker.

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

#5


0  

\$\{title\}

\ $ \ {标题\}

#6


0  

In Regular Expression the escape character is \ to use this we have to write \\ as in String, \ is use as escape character.

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

For example str = str.replaceAll("rot\\*speed", "rotorspeed");

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

rot*speed will be replace with rotorspeed .

rot * speed将被rotorspeed取代。