• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 787
  • Last Modified:

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?
0
jellis613
Asked:
jellis613
  • 2
  • 2
1 Solution
 
Jesse HouwingScrum Trainer | Microsoft MVP | ALM Ranger | ConsultantCommented:
$number is a reserved combination used to insert numbered groups into a search result. To escape these you should double the '$'.

REPLACEMENT_STRING = "$$0 to $$1K"

Just to explain how this works:

If your regex is like this: @"<@([^@]+)@>"" (which will match any of your include strings) with your example string:   @"\<\@REVENUE_POTENTIAL\@\>" then

$0 will be: the whole string: <@REVENUE_POTENTIAL@>
$1 will be: the part between the first set of braces: REVENUE_POTENTIAL

but:
$$0 will just be $0
$$1 will just be $1

If there is no numbered group then $number will just remain $number.
0
 
jellis613Author Commented:
I added the line:
if (REVENUE_POTENTIAL.Substring(0,3) == "$0 ") {
      REVENUE_POTENTIAL = "$" + REVENUE_POTENTIAL;
}
and it now works. Thanks!
0
 
Jesse HouwingScrum Trainer | Microsoft MVP | ALM Ranger | ConsultantCommented:
It would be even better to just escape all the '$' with '$$' just in case the regex ever changes.
0
 
jellis613Author Commented:
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,"$$$$");
0

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now