示例:扫描 HREF
更新:2007 年 11 月
下面的示例搜索输入字符串并输出所有 href="…" 的值和它们在字符串中的位置。
Regex 对象
因为 Regex 对象用在 DumHRefs 方法中(可以从用户代码多次调用该方法),所以将使用 static(在 Visual Basic 中为 Shared)Regex.Match(String, String, RegexOptions) 方法。这使得正则表达式引擎可以缓存正则表达式,并避免在每次调用该方法时实例化新的 Regex 对象所造成的开销。随后,将使用一个 Match 对象来循环访问字符串中的所有匹配项。在此示例中,元字符 \s 匹配任何空白字符,\S 匹配任何非空白字符。
Private Sub DumpHRefs(inputString As String)
Dim m As Match
Dim HRefPattern As String = "href\s*=\s*(?:""(?<1>[^""]*)""|(?<1>\S+))"
m = Regex.Match(inputString, HRefPattern, _
RegexOptions.IgnoreCase Or RegexOptions.Compiled)
Do While m.Success
Console.WriteLine("Found href {0} at {1}.", _
m.Groups(1), m.Groups(1).Index)
m = m.NextMatch()
Loop
End Sub
private static void DumpHRefs(string inputString)
{
Match m;
string HRefPattern = "href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))";
m = Regex.Match(inputString, HRefPattern,
RegexOptions.IgnoreCase | RegexOptions.Compiled);
while (m.Success)
{
Console.WriteLine("Found href " + m.Groups[1] + " at "
+ m.Groups[1].Index);
m = m.NextMatch();
}
}
然后,下面的示例演示对 DumHRefs 方法的调用。
Public Sub Main()
Dim inputString As String = "My favorite web sites include:</P>" & _
"<A HREF=""https://msdn2.microsoft.com"">" & _
"MSDN Home Page</A></P>" & _
"<A HREF=""https://www.microsoft.com"">" & _
"Microsoft Corporation Home Page</A></P>" & _
"<A HREF=""https://blogs.msdn.com/bclteam"">" & _
".NET Base Class Library blog</A></P>"
DumpHRefs(inputString)
End Sub
' The example displays the following output:
' Found href https://msdn2.microsoft.com at 43
' Found href https://www.microsoft.com at 102
' Found href https://blogs.msdn.com/bclteam/) at 176
public static void Main()
{
string inputString = "My favorite web sites include:</P>" +
"<A HREF=\"https://msdn2.microsoft.com\">" +
"MSDN Home Page</A></P>" +
"<A HREF=\"https://www.microsoft.com\">" +
"Microsoft Corporation Home Page</A></P>" +
"<A HREF=\"https://blogs.msdn.com/bclteam\">" +
".NET Base Class Library blog</A></P>";
DumpHRefs(inputString);
}
// The example displays the following output:
// Found href https://msdn2.microsoft.com at 43
// Found href https://www.microsoft.com at 102
// Found href https://blogs.msdn.com/bclteam at 176
匹配结果类
搜索的结果存储在 Match 类中,这提供对该搜索提取的所有子字符串的访问。因为该类还记忆所搜索的字符串和所使用的正则表达式,所以它还可以使用这些字符串和表达式来在上一次搜索结束的地方开始另一个搜索。
显式命名的捕获
在传统的正则表达式中,捕获括号是自动按顺序编号的。这导致了两个问题。首先,如果通过插入或移除一组括号修改了一个正则表达式,则必须重写所有引用编号捕获的代码以反映新的编号。其次,因为不同的括号组经常被用来为可接受的匹配提供两个可替换的表达式,所以可能比较难于确定哪一个可替换的表达式实际返回了结果。
为解决这些问题,Regex 支持将匹配捕获到指定槽中的语法 (?<name>…)(可以用字符串或整数命名槽;但整数可以被更快地回调。)因此,同一字符串的所有替换匹配都可被定向到同一位置。如果出现冲突,放置到槽中的最后一个匹配将是成功的匹配。(但是,单个槽的多个匹配的完整列表是可用的。有关详细信息,请参见 Group.Captures 集合。)