用正则表达式替换C#美元问题

时间:2010-12-02 18:29:14

标签: c# .net regex

我想在两个指定的捕获组之间的特定位置插入一个美元符号。问题是,这意味着两个紧跟在替换字符串中的美元符号之后会导致问题。

如何使用Replace-method直接执行此操作?我只是通过添加一些我立即删除的临时垃圾找到了一种解决方法。

请参阅问题代码:

      // 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.

2 个答案:

答案 0 :(得分:12)

使用此替换模式:"${start}$$${end}"

$$转义$,以便将其视为文字字符。第三个$实际上是命名组${end}的一部分。您可以在MSDN Substitutions page上阅读此内容。

我会坚持上述方法。或者,您可以使用接受Replace的{​​{1}}重载并连接所需内容,类似于以下内容:

MatchEvaluator

答案 1 :(得分:2)

为什么你首先使用正则表达式?

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

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