2008-11-21 125 views
3

我正在使用strips the href tags out of an html doc保存到字符串的正则表达式。以下代码是我在C#控制台应用程序中使用它的方式。为什么Regex.Match只返回1个结果?

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

如果使用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(); 
15

匹配方法搜索字符串的第一次出现,匹配方法搜索所有发生。

+0

只是想知道,我必须要改变`匹配M`为`MatchCollections M`使用Regex.Matches()方法,但后来它说'MatchCollections`没有对`的定义m.success`。有什么我失踪? – MattSayar 2008-11-24 14:39:42

+1

@Matt S - 如果有匹配,它的长度> 0 – 2008-11-24 20:19:17