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_POTENTIA L);
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?
string message = <@REVENUE_POTENTIAL@>;
const string VAR_REVENUE_POTENTIAL = @"\<\@REVENUE_POTENTIAL\@\
Regex reg = new Regex(VAR_REVENUE_POTENTIA
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
It would be even better to just escape all the '$' with '$$' just in case the regex ever changes.
ASKER
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(RE PLACEMENT_ STRING,"$$ $$");
Regex regMatchDollars = new Regex(@"\$"); // Matches any one dollar sign
...
REPLACEMENT_STRING = regMatchDollars.Replace(RE
ASKER
if (REVENUE_POTENTIAL.Substri
REVENUE_POTENTIAL = "$" + REVENUE_POTENTIAL;
}
and it now works. Thanks!