一般来说,这是不可能的。正则表达式匹配引擎并非真正设计用于查找重叠匹配。一个快速的解决方案是手动检查所有子字符串的模式:
string text = "1123322";
for (int start = 0; start < text.Length - 1; start++)
{
for (int length = 0; length <= text.Length - start; length++)
{
string subString = text.Substring(start, length);
if (Regex.IsMatch(subString, "^1.*2$"))
Console.WriteLine("{0}-{1}: {2}", start, start + length, subString);
}
}
工作示例:http://ideone.com/aNKnJ
现在,是否有可能获得完整的正则表达式解决方案?大多数情况下,答案是否定的。然而,.Net 确实有一些技巧可以帮助我们:它允许可变长度的后视,并允许每个捕获组记住所有捕获(大多数引擎只返回每个组的最后一个匹配项)。滥用这些,我们可以在正则表达式引擎中模拟相同的for 循环:
string text = "1123322!";
string allMatchesPattern = @"
(?<=^ # Starting at the local end position, look all the way to the back
(
(?=(?<Here>1.*2\G))? # on each position from the start until here (\G),
. # *try* to match our pattern and capture it,
)* # but advance even if you fail to match it.
)
";
MatchCollection matches = Regex.Matches(text, allMatchesPattern,
RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace);
foreach (Match endPosition in matches)
{
foreach (Capture startPosition in endPosition.Groups["Here"].Captures)
{
Console.WriteLine("{0}-{1}: {2}", startPosition.Index,
endPosition.Index - 1, startPosition.Value);
}
}
请注意,目前存在一个小错误 - 引擎不会尝试匹配最后一个结束位置 ($),因此您会丢失一些匹配项。目前,在字符串末尾添加 ! 即可解决该问题。
工作示例:http://ideone.com/eB8Hb