【问题标题】:How to write regular expression for found href of a tags? [duplicate]如何为找到的标签的href编写正则表达式? [复制]
【发布时间】:2016-01-18 00:55:17
【问题描述】:

我需要在这样的字符串中找到标签的href。

<li><a href="http://bipardeh94.blogfa.com" target="_blank">باغ بلور</a><span class="ur">bipardeh94.blogfa.com</span><span class="ds">فرهنگی-خبری-علمی</span></li>
    <li><a href="http://avaejam.blogfa.com" target="_blank">هزار نکته </a><span class="ur">avaejam.blogfa.com</span><span class="ds"> يك نكته از هزار نكته  باشد تا بعد </span></li>
    <li><a href="http://prkangavar.blogfa.com" target="_blank">روابط عمومی دانشگاه آزاداسلامی کنگاور</a><span class="ur">prkangavar.blogfa.com</span><span class="ds">اخبار دانشگاه</span></li>

我使用这个代码:

   string regex = "href=\"(.*)\"";
        Match match = Regex.Match(codeHtml, regex);
        if (match.Success)
        {
            textBox1.Text += match.Value +"\n";
        }

这段代码先找到href,然后返回所有代码。

【问题讨论】:

    标签: html regex


    【解决方案1】:

    这个正则表达式有效吗?

    string regex = "href=\"([^\"]*)\"";
    

    [^\"]* 允许 href 引号内的所有内容都不是引号

    如何匹配所有标签,请使用Regex.Matches

    【讨论】:

    • 我用这个。这仅返回一个 href,例如 ( href="akhbarearesht.blogfa.com" )。我想返回存在于 href attr 中的所有链接,例如 (akhbarearesht.blogfa.com)
    • @programmer138200,确保您使用Matches 来查找多个出现。 Match 只找到第一个。
    • 我将匹配更改为匹配但出现错误。如何更改我的代码来解决此问题?
    • @programmer138200 请查看 Regex.Matches 方法文档msdn.microsoft.com/en-gb/library/…。具体来说,例子
    • 我使用此代码并出售( foreach (Match m in Regex.Matches(input, pattern)) )。 Joseph Young 非常感谢您
    猜你喜欢
    • 2014-01-17
    • 1970-01-01
    • 2016-11-15
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    相关资源
    最近更新 更多