正则表达式替换的C#美元问题 [英] C# dollar problem with regex-replace
问题描述
我想在两个命名的捕获组之间的特定位置插入美元符号。问题是这意味着替换字符串中紧随两个美元符号会导致问题。
I want to insert a dollar sign at a specific position between two named capturing groups. The problem is that this means two immediately following dollar-signs in the replacement-string which results in problems.
我如何直接使用替换方法?我只是找到了一种解决方法,方法是添加一些临时垃圾,然后立即将其再次删除。
请参阅该问题的代码:
// 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.
推荐答案
使用以下替换模式: $ {start} $$$ {end}
双精度 $$
转义 $
,以便将其视为文字字符。第三个 $
实际上是命名组 $ {end}
的一部分。您可以在MSDN 替换页面中了解其内容。
The double $$
escapes the $
so that it is treated as a literal character. The third $
is really part of the named group ${end}
. You can read about this on the MSDN Substitutions page.
我会坚持使用上述方法。或者,您可以使用 Replace
重载,该重载接受 MatchEvaluator
并连接所需的内容,类似于以下内容:
I would stick with the above approach. Alternately you can use the Replace
overload that accepts a MatchEvaluator
and concatenate what you need, similar to the following:
jackHas = dollarInsertion.Replace(jackHas,
m => m.Groups["start"].Value + "$" + m.Groups["end"].Value);
这篇关于正则表达式替换的C#美元问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!