伯爵正则表达式替换(C#)

编程入门 行业动态 更新时间:2024-10-10 07:27:40
本文介绍了伯爵正则表达式替换(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有没有一种方法来计算替换的数量Regex.Replace调用使?

Is there a way to count the number of replacements a Regex.Replace call makes?

例如。为 Regex.Replace(AAA,A,B); 我想获得3号出(结果是BBB );为 Regex.Replace(AAA,(小于?试验> AA),$ {测试} B); 我想获得数2出(结果是aabab的)。

E.g. for Regex.Replace("aaa", "a", "b"); I want to get the number 3 out (result is "bbb"); for Regex.Replace("aaa", "(?<test>aa?)", "${test}b"); I want to get the number 2 out (result is "aabab").

方法,我能想到做到这一点:

Ways I can think to do this:

  • 使用递增捕获的变量,如果用手工更换了MatchEvaluator
  • 获取一个MatchCollection和重复它,如果用手工更换,并保持一个计数
  • 搜索第一,并获得MatchCollection,得到的计数,然后做一个单独的替换
  • 方法1和2需要更换$手工解析,方法3要求的正则表达式匹配字符串的两倍。有没有更好的办法。

    Methods 1 and 2 require manual parsing of $ replacements, method 3 requires regex matching the string twice. Is there a better way.

    推荐答案

    由于双方Chevex和Guffa。我开始寻找更好的方式来获得满意的结果,发现有上做替代匹配类结果的方法。这就是缺少一块拼图。下面的例子code:

    Thanks to both Chevex and Guffa. I started looking for a better way to get the results and found that there is a Result method on the Match class that does the substitution. That's the missing piece of the jigsaw. Example code below:

    using System.Text.RegularExpressions; namespace regexrep { class Program { static int Main(string[] args) { string fileText = System.IO.File.ReadAllText(args[0]); int matchCount = 0; string newText = Regex.Replace(fileText, args[1], (match) => { matchCount++; return match.Result(args[2]); }); System.IO.File.WriteAllText(args[0], newText); return matchCount; } } }

    通过一个包含文件test.txt AAA,在命令行 regexrep的test.txt(小于?试验&gt; AA)$ {}测试b 将设置%ERRORLEVEL%,至2,切换到aabab的文本。

    With a file test.txt containing aaa, the command line regexrep test.txt "(?<test>aa?)" ${test}b will set %errorlevel% to 2 and change the text to aabab.

    更多推荐

    伯爵正则表达式替换(C#)

    本文发布于:2023-11-06 03:35:53,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1562623.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:伯爵   正则表达式

    发布评论

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

    >www.elefans.com

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