示例:扫描 HREF(From MSDN)以下示例搜索输入字符串并输出所有 href=“...”值和它们在字符串中的位置。它执行此操作的方式为,首先构造编译的 Regex 对象,然后使用 Match 对象来循环访问字符串中的所有匹配。在下面的代码示例中,元字符 \s 匹配任何空白字符,\S 匹配任何非空白字符。[Visual Basic] Sub DumpHrefs(inputString As String) Dim r As Regex Dim m As Match
r = New Regex("href\s*=\s*(?:""(?<1>[^""]*)""|(?<1>\S+))", _ RegexOptions.IgnoreCase Or RegexOptions.Compiled)
m = r.Match(inputString) While m.Success Console.WriteLine("Found href " & m.Groups(1).Value _ & " at " & m.Groups(1).Index.ToString()) m = m.NextMatch() End While End Sub [C#] void DumpHrefs(String inputString) { Regex r; Match m; r = new Regex("href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))", RegexOptions.IgnoreCase|RegexOptions.Compiled); for (m = r.Match(inputString); m.Success; m = m.NextMatch()) { Console.WriteLine("Found href " + m.Groups[1] + " at " + m.Groups[1].Index); } }
Sub DumpHrefs(inputString As String)
Dim r As Regex
Dim m As Match
r = New Regex("href\s*=\s*(?:""(?<1>[^""]*)""|(?<1>\S+))", _
RegexOptions.IgnoreCase Or RegexOptions.Compiled)
m = r.Match(inputString)
While m.Success
Console.WriteLine("Found href " & m.Groups(1).Value _
& " at " & m.Groups(1).Index.ToString())
m = m.NextMatch()
End While
End Sub
[C#]
void DumpHrefs(String inputString)
{
Regex r;
Match m; r = new Regex("href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))",
RegexOptions.IgnoreCase|RegexOptions.Compiled);
for (m = r.Match(inputString); m.Success; m = m.NextMatch())
{
Console.WriteLine("Found href " + m.Groups[1] + " at "
+ m.Groups[1].Index);
}
}