计数正则表达式替换 (C#) [英] Count regex replaces (C#)
问题描述
有没有办法计算 Regex.Replace 调用的替换次数?
Is there a way to count the number of replacements a Regex.Replace call makes?
例如for Regex.Replace("aaa", "a", "b");
我想得到数字 3(结果是 "bbb"
);for Regex.Replace("aaa", "(?<test>aa?)", "${test}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"
).
我能想到的方法:
- 使用 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.我开始寻找一种更好的方法来获得结果,并发现 Match 类中有一个 Result 方法可以进行替换.那是拼图缺失的那一块.下面的示例代码:
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;
}
}
}
对于包含 aaa 的文件 test.txt,命令行 regexrep test.txt "(?<test>aa?)" ${test}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屋!