我正在寻找一种使用c#regex.replace函数在替换表达式中使用匹配组长度的方法.
I'm looking for a way to use the length of a match group in the replace expression with the c# regex.replace function.
也就是说,我可以替换什么???在下面的示例中用来获得所需的输出,如下所示?
That is, what can I replace ??? with in the following example to get the desired output shown below?
示例:
val = Regex.Replace("xxx", @"(?<exes>x{1,6})", "${exes} - ???");所需的输出
X - 3注意:这是一个极度设计/简化的示例,用于演示该问题.我意识到在此示例中,使用正则表达式不是实现此目的的理想方法.请相信我,答案的实际应用是一个更复杂问题的一部分,确实需要在此处使用RegEx替换.
Note: This is an extremely contrived/simplified example to demonstrate the question. I realize for this example a regular expression is not the ideal way of doing this. Just trust me that the real world application of the answer is part of a more complex problem that does necessitate the use of a RegEx replace here.
推荐答案尝试使用 Regex.Replace 版本,该版本调用一个函数来确定替换文本应为:
Try using the version of Regex.Replace that calls a function to determine what the replacement text should be:
public string Replace(string, MatchEvaluator);msdn.microsoft/en-us/library/aa332127(VS.71).aspx
然后该函数可以查看匹配的文本( The function could then look at the matched text (the Match object is supplied as the argument to the evaluator function) and return a string with the proper calculated value.
更多推荐
如何在C#中的RegEx替换操作中使用计算值?
发布评论