【发布时间】:2018-10-30 03:02:57
【问题描述】:
如果我有一些文字:
string myText = "01001001 -This is the first line\r\n" +
"01001002 -This is the 2nd line\r\n" +
"01002003 This is the third line\r\n";
我有一个正则表达式替换命令:
string searchPattern = "([0-9]{8}) -([^-])?";
string replacePatten = "$1 xx$2";
RegEx.Replace(myText,searchPatten,replacePattern);
这很好,我得到了结果:
myText = "01001001 xxThis is the first line\r\n" +
"01001002 xxThis is the 2nd line\r\n" +
"01002003 This is the third line\r\n";
但是,我真正想要的是类似于 RegEx.Matches 的东西,除了我还想知道替换字符串是什么。所以像:
Matches matches = RegEx.Matches(myText,searchPattern,replacePattern);
这将产生一个包含两个结果的匹配集合。我会知道每场比赛的索引和长度以及它将被替换的内容:
matches[0].ToString() = {Index=0,Length=10,ReplacedWith="01001001 xxThis is the first line\r\n"}
matches[1].ToString() = {Index=36,Length=10,ReplacedWith="01001002 xxThis is the second line\r\n"}
所以我希望能够在不实际替换的情况下计算替换字符串。我查看了 MatchEvaluator Delegates,但我不知道如何将它与与 searchPattern 绑定的 replacePattern 一起使用。
【问题讨论】:
-
看来你想要
RegEx.Matches(myText,searchPatten).Cast<Match>().Select(x => $"{x.Groups[1].Value} xx{x.Groups[2].Value}") -
您是正确的,您的答案将适用于特定的 replacePattern,但我需要任何 searchPattern 和 replacePattern 的通用解决方案。抱歉,应该更清楚地说明一般解决方案的要求。