I’d like to manipulate a String in Java using Regex. Goal is to find all $ signs that have an even number of \ in front of them (or none) and then add another \.
Example:
"$ Find the $ to \$ escape \\$ or not \\\$ escape \\\\$ like here $"
should result in:
"\$ Find the \$ to \$ escape \\\$ or not \\\$ escape \\\\\$ like here \$"
Rationale here is: some $ are already escaped with a \ and some escape \ might be in the string as well in the form of \\. I need to escape the remaining $.
This should do the work: replace:
with the whole text matched (except for the lookahead), followed by
\\.Illustration in perl:
With Java, the whole text match is
$0. Sample code:Output:
A little explanation about the regex used is in order:
To be really complete, here are the positions at which the regex engine will find matching text (symbolized with
<>) and the cursor position (symbolized by|):