Problem with c # dollar with regex-replace

I want to insert a dollar sign at a specific position between two named capture groups. The problem is that this means two immediately after the dollar sign in the replacement string, which leads to problems.

How can I do this directly using the Replace method? I found a workaround by adding some temporary garbage that I delete again again.

See problem code:

      // We want to add a dollar sign before a number and use named groups for capturing;
      // varying parts of the strings are in brackets []
      // [somebody] has [some-dollar-amount] in his [something]

      string joeHas = "Joe has 500 in his wallet.";
      string jackHas = "Jack has 500 in his pocket.";
      string jimHas = "Jim has 740 in his bag.";
      string jasonHas = "Jason has 900 in his car.";

      Regex dollarInsertion = new Regex(@"(?<start>^.*? has )(?<end>\d+ in his .*?$)", RegexOptions.Multiline);

      Console.WriteLine(joeHas);
      Console.WriteLine(jackHas);
      Console.WriteLine(jimHas); 
      Console.WriteLine(jasonHas);
      Console.WriteLine("--------------------------");

      joeHas = dollarInsertion.Replace(joeHas, @"${start}$${end}");
      jackHas = dollarInsertion.Replace(jackHas, @"${start}$-${end}");          
      jimHas = dollarInsertion.Replace(jimHas, @"${start}\$${end}");
      jasonHas = dollarInsertion.Replace(jasonHas, @"${start}$kkkkkk----kkkk${end}").Replace("kkkkkk----kkkk", "");

      Console.WriteLine(joeHas);
      Console.WriteLine(jackHas);
      Console.WriteLine(jimHas);
      Console.WriteLine(jasonHas);




Output:
Joe has 500 in his wallet.
Jack has 500 in his pocket.
Jim has 740 in his bag.
Jason has 900 in his car.
--------------------------
Joe has ${end}
Jack has $-500 in his pocket.
Jim has \${end}
Jason has $900 in his car.
+5
source share
2 answers

Use this replacement template: "${start}$$${end}"

$$ $, . $ ${end}. MSDN .

. Replace, MatchEvaluator , , :

jackHas = dollarInsertion.Replace(jackHas,
              m => m.Groups["start"].Value + "$" + m.Groups["end"].Value);
+12

-?

string name = "Joe";
int amount = 500;
string place = "car";

string output = string.Format("{0} has ${1} in his {2}",name,amount,place);
+2

All Articles