Jay
Jay

Reputation: 20136

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)

Upvotes: 15

Views: 11508

Answers (6)

kuriouscoder
kuriouscoder

Reputation: 5582

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

Upvotes: 6

Krushna
Krushna

Reputation: 1

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 .

Upvotes: 0

ratchet freak
ratchet freak

Reputation: 48196

the Pattern class has a escape function for uses like this

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

Upvotes: 25

daalbert
daalbert

Reputation: 1475

\$\{title\}

Upvotes: 0

kuriouscoder
kuriouscoder

Reputation: 5582

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

Upvotes: 1

BoltClock
BoltClock

Reputation: 723688

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

Upvotes: 17

Related Questions