如何在不执行替换的情况下获取正则表达式的替换字符串?
解决思路:获取正则匹配的位置信息+对应替换结果
我明白你的需求了——你不需要直接修改原文本,而是想要逐个获取每个正则匹配项的Index、Length,同时得到该匹配按照指定替换模式生成的结果,对吧?其实不用纠结MatchEvaluator的复杂用法,我们可以结合Regex.Matches和Match.Result()方法轻松实现这个需求,而且和Regex.Replace的替换逻辑完全一致。
原代码回顾
先看你给出的原始文本和正则定义:
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 replacePattern = "$1 xx$2";
实现方案:遍历匹配+获取替换结果
我们可以先通过Regex.Matches拿到所有匹配项,然后对每个Match对象:
- 直接获取
Index和Length属性,得到匹配的位置信息 - 调用
Match.Result(replacePattern)方法,自动生成该匹配对应的替换后字符串(这个方法会自动处理替换模式里的捕获组,和Regex.Replace的替换逻辑完全一致)
下面是完整的示例代码:
using System; using System.Text.RegularExpressions; using System.Collections.Generic; // 定义一个类来存储每个匹配的信息 public class MatchReplacementInfo { public int Index { get; set; } public int Length { get; set; } public string OriginalMatch { get; set; } public string ReplacedValue { get; set; } } class Program { static void Main() { 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 replacePattern = "$1 xx$2"; List<MatchReplacementInfo> matchInfos = new List<MatchReplacementInfo>(); // 遍历所有匹配项 foreach (Match match in Regex.Matches(myText, searchPattern)) { if (match.Success) { matchInfos.Add(new MatchReplacementInfo { Index = match.Index, Length = match.Length, OriginalMatch = match.Value, ReplacedValue = match.Result(replacePattern) // 核心:生成替换结果 }); } } // 输出结果示例 foreach (var info in matchInfos) { Console.WriteLine($"匹配位置:Index={info.Index}, Length={info.Length}"); Console.WriteLine($"原匹配内容:{info.OriginalMatch}"); Console.WriteLine($"替换后内容:{info.ReplacedValue}\n"); } } }
结果说明
运行这段代码后,你会得到每个匹配的详细信息:
- 前两个匹配项(
01001001 -T和01001002 -T)会被替换为01001001 xxT和01001002 xxT - 第三个字符串
01002003 This...因为没有-紧跟8位数字,所以不会被匹配到
关于MatchEvaluator的补充
如果你一定要用MatchEvaluator,其实也可以在遍历匹配的时候调用它,比如:
MatchEvaluator evaluator = match => match.Result(replacePattern); // 对每个match,调用evaluator(match)就能得到替换结果
不过Match.Result()已经足够简洁,不需要额外封装委托啦。
内容的提问来源于stack exchange,提问作者ccampj
相关产品推荐
相关产品推荐

