如何在C#中的RegEx替换操作中使用计算值?

编程入门 行业动态 更新时间:2024-10-11 07:32:25
本文介绍了如何在C#中的RegEx替换操作中使用计算值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在寻找一种使用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替换操作中使用计算值?

本文发布于:2023-10-31 09:09:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545683.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:操作   如何在   RegEx

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!