Link to home
Start Free TrialLog in
Avatar of jellis613
jellis613

asked on

Regex.Replace Malfunction when inserting "$0"

I have the following code:
string message = <@REVENUE_POTENTIAL@>;
const string VAR_REVENUE_POTENTIAL  = @"\<\@REVENUE_POTENTIAL\@\>";
Regex reg = new Regex(VAR_REVENUE_POTENTIAL);
message = reg.Replace(message, REPLACEMENT_STRING);

When REPLACEMENT_STRING = "$0 to $1K", after the Replacement is performed, message (bad) = "<@REVENUE_POTENTIAL@> to $1K"
When REPLACEMENT_STRING = something else (like "$1K to $5K, etc), then message (good) = "$1K to $5K"

For some reason, when REPLACEMENT_STRING begins with the characters $0, this part of the string is not replaced - instead, the rest of the replacement string is appended to the original text (which is not deleted). I have tried this with other digits (ie: strings beginning with $1, etc) and it works fine. It seems to only be happening when the replacement string begins with $0.

Why is this happening?
ASKER CERTIFIED SOLUTION
Avatar of Jesse Houwing
Jesse Houwing
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jellis613
jellis613

ASKER

I added the line:
if (REVENUE_POTENTIAL.Substring(0,3) == "$0 ") {
      REVENUE_POTENTIAL = "$" + REVENUE_POTENTIAL;
}
and it now works. Thanks!
It would be even better to just escape all the '$' with '$$' just in case the regex ever changes.
I have taken your advice and implemented a replacement of every single $ sign with $$, in all of my parameters:

Regex regMatchDollars = new Regex(@"\$"); // Matches any one dollar sign
...
REPLACEMENT_STRING = regMatchDollars.Replace(REPLACEMENT_STRING,"$$$$");