伯爵正则表达式替换(C#) [英] Count regex replaces (C#)

查看:152
本文介绍了伯爵正则表达式替换(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:

  1. 使用递增捕获的变量,如果用手工更换了MatchEvaluator
  2. 获取一个MatchCollection和重复它,如果用手工更换,并保持一个计数
  3. 搜索第一,并获得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#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆