回溯
更新:2007 年 11 月
当正则表达式具有可选的或替换的匹配模式时,该正则表达式在其输入字符串的计算的某些点上,可以分支到一个或多个方向以完成所有可能的匹配。如果匹配在引擎搜索的第一个方向不成功,则它必须备份产生分支的输入字符串中的这一位置并尝试其他替换的匹配。
例如,假定设计一个正则表达式来匹配灰色一词的两种拼写形式:gray 和 grey。替换字符 | 用于创建正则表达式 gr(a|e)y,它可以与两种拼法中的任何一种匹配。当该正则表达式应用到输入字符串 greengraygrowngrey 时,假设引擎首先尝试匹配 gray。它与输入字符串中的前两个字符 gr 匹配,遇到 green 中的 e 后匹配失败。它回溯到 r(替换字符前的上一个成功匹配)并尝试匹配 grey。在第二个 e 上匹配失败,引擎继续搜索并将最终匹配两个嵌入的单词 gray 和 grey。
下面的代码示例表明如何创建此正则表达式并将其应用到输入字符串。
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
' Define strings: "gray" and "grey".
Dim r As New Regex("gr(a|e)y")
Dim m As MatchCollection = r.Matches("greengraygrowngrey")
Console.WriteLine("Number of groups found: {0}", m.Count)
End Sub
End Module
' The example displays the following output:
' Number of groups found: 2
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
// Define strings: "gray" and "grey".
Regex r = new Regex("gr(a|e)y");
MatchCollection m = r.Matches("greengraygrowngrey");
Console.WriteLine("Number of groups found: {0}", m.Count);
}
}
// The example displays the following output:
// Number of groups found: 2