加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 19:41:07 所属栏目:百科 来源:网络整理
导读:我正在使用 strips the href tags out of an html doc保存为字符串的正则表达式.以下代码是我在C#控制台应用程序中使用它的方式. Match m = Regex.Match(htmlSourceString,"href=["'](http://|./|/)?w+(.w+)*(/w+(.w+)?)*(/|?w*=w*(w
我正在使用 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语句有什么东西不允许我返回所有结果吗?

解决方法

如果使用Match而不是Matches,则需要使用循环来获取在每个循环结束时调用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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读