Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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)
like image 215
Jay Avatar asked May 19 '11 23:05

Jay


People also ask

How do you exit the dollar sign in Java?

In Java, an unescaped dollar sign that doesn't form a token is an error. You must escape the dollar sign with a backslash or another dollar sign to use it as a literal character. $! is an error because the dollar sign is not escaped and has no special meaning in combination with the exclamation point.

How do you escape the dollar sign in regex?

Try escaping with \\\ on the dollar signs. It might be okay to infer a relationship between the problem dollar sign and the fact that PHP uses $ to do some work.

How do you escape brackets in regex Java?

The first backslash escapes the second one into the string, so that what regex sees is \] . Since regex just sees one backslash, it uses it to escape the square bracket. In regex, that will match a single closing square bracket. If you're trying to match a newline, for example though, you'd only use a single backslash.

How do you escape curly braces in regular expression?

To match literal curly braces, you have to escape them with \ . However, Apex Code uses \ as an escape, too, so you have to "escape the escape". You'll need to do this almost every time you want to use any sort of special characters in your regexp literally, which will happen more frequently than not.


3 Answers

the Pattern class has a escape function for uses like this

string.replaceAll(Pattern.quote("${title}"), title);
like image 162
ratchet freak Avatar answered Nov 07 '22 19:11

ratchet freak


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);
like image 40
BoltClock Avatar answered Nov 07 '22 20:11

BoltClock


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

like image 42
kuriouscoder Avatar answered Nov 07 '22 19:11

kuriouscoder