开发者

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开发者_StackOverflow中文版.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)


the Pattern class has a escape function for uses like this

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


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


This sounds like a typical use case of template language such as 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 .

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜