简体   繁体   中英

How do you escape dollar and braces, (i.e. ${title}) in a java regular expression?

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)

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

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

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

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

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

\\$\\{title\\}

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

rot*speed will be replace with rotorspeed .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM