Проблема доллара в C # с заменой регулярного выражения

Я хочу вставить знак доллара в определенную позицию между двумя именованными группами захвата. Проблема в том, что это означает, что в строке замены сразу идут два знака доллара, что приводит к проблемам.

Как я могу сделать это напрямую с помощью метода Replace? Я нашел обходной путь, только добавив временный мусор, который я немедленно удаляю снова.

См. Код проблемы:

      // 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
задан Ahmad Mageed 2 December 2010 в 18:44
поделиться