为什么Regex.Match只返回1个结果?

时间:2008-11-21 21:41:51

标签: c# html regex

我正在使用strips the href tags out of an html doc保存到字符串的正则表达式。以下代码是我在C#控制台应用程序中使用它的方式。

Match m = Regex.Match(htmlSourceString, "href=[\\\"\\\'](http:\\/\\/|\\.\\/|\\/)?\\w+(\\.\\w+)*(\\/\\w+(\\.\\w+)?)*(\\/|\\?\\w*=\\w*(&\\w*=\\w*)*)?[\\\"\\\']");

        if (m.Success)
        {
            Console.WriteLine("values = " + m);
        }

但是,它只返回一个结果,而不是html页面上所有href标记的列表。我知道它有效,因为当我尝试RegexOptions.RightToLeft时,它返回字符串中的最后一个href标签。

我的if语句中是否有某些内容不允许我返回所有结果?

2 个答案:

答案 0 :(得分:17)

匹配方法搜索字符串的第一个出现位置,匹配方法搜索所有出现的内容。

答案 1 :(得分:2)

如果使用Match而不是Match es ,则需要使用循环来获取在每个循环结束时调用m.NextMatch()的所有匹配项。例如:

    Match m = Regex.Match(htmlSourceString, "href=[\\\"\\\'](http:\\/\\/|\\.\\/|\\/)?\\w+(\\.\\w+)*(\\/\\w+(\\.\\w+)?)*(\\/|\\?\\w*=\\w*(&\\w*=\\w*)*)?[\\\"\\\']");
    Console.Write("values = ");
    while (m.Success) 
    { 
        Console.Write(m.Value);
        Console.Write(", "); // Delimiter
        m = m.NextMatch();
    }
    Console.WriteLine();
相关问题