以下示例搜索输入字符串并打印出字符串中的所有href =“...”值及其位置。它通过构造一个已编译的Regex对象,然后使用Match对象迭代字符串中的所有匹配来完成此操作。在此示例中,元字符匹配任何空格字符,\ S匹配任何非空格字符。
'VB
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结束子
// 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);
}}