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)
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.
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.
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.
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.
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);
This sounds like a typical use case of template language such as FreeMarker.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With