伯爵正则表达式替换(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调用使?

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.

阅读全文

相关推荐

最新文章