使用 regex.matches 获取所有匹配后,通过遍历索引并检查相邻匹配的结束位置是否大于下一个匹配的开始位置来找出重叠结果。默认情况下正则引擎不会返回重叠匹配,因此需要手动处理索引偏移或结合前瞻断言来实现。

Regex.Matches 返回的集合如何用于检测重叠?
Regex.Matches 方法返回一个 MatchCollection,其中每个 Match 对象包含 Index 和 Length 属性。要判断两个匹配是否重叠,只需比较当前匹配的结束索引(Index + Length)与下一个匹配的开始索引(Next.Index)。如果前者大于后者,则存在重叠部分。

using System;
using System.Text.RegularExpressions;
public class Program {
public static void Main() {
string text = "abcabc";
string pattern = "abc";
MatchCollection matches = Regex.Matches(text, pattern);
for (int i = 0; i next.Index) {
Console.WriteLine($"Overlap found: '{current.Value}' and '{next.Value}'");
}
}
}
}
如何使用前瞻断言实现自动重叠匹配?
利用零宽断言(Lookahead),可以在不消耗字符的情况下进行多次匹配。例如,使用 (?=(pattern)) 结构,正则引擎会在每个位置尝试匹配,如果成功则记录匹配内容但不移动指针,从而自然产生重叠结果。这种方法无需手动检查索引,直接由正则引擎完成。

using System;
using System.Text.RegularExpressions;
public class Program {
public static void Main() {
string text = "aaaa";
// 使用前瞻捕获重叠的 "aa"
string pattern = @"(?=(aa))";
MatchCollection matches = Regex.Matches(text, pattern);
foreach (Match match in matches) {
if (match.Success && match.Groups[1].Success) {
Console.WriteLine($"Found: '{match.Groups[1].Value}' at index {match.Index}");
}
}
}
}
在输入字符串为 "aba" 时,模式 "a.b" 的重叠情况如何?
对于输入 "aba" 和模式 "a.b",默认 Regex.Matches 会找到第一个匹配 "aba"(索引 0-2),然后从索引 3 开始搜索,没有更多匹配。但如果使用前瞻模式 (?=(a.b)),则在索引 0 处匹配 "aba",在索引 1 处无法匹配 "a.b"(因为剩余字符是 "ba",长度不足且不符合模式),因此只有一个匹配。若模式改为 "ab",则无重叠。关键在于模式是否能跨重叠区域再次匹配。











