【问题标题】:A pattern to parse links in a text [duplicate]解析文本中链接的模式[重复]
【发布时间】:2014-03-12 13:35:10
【问题描述】:

我有一些文本可能包含这样的链接:

<a rel="nofollow" target="_blank" href="http://loremipsum.net/">http://loremipsum.net/</a>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, <a rel="nofollow" target="_blank" href="http://loremipsum.net/">http://loremipsum.net/</a> sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

我想在此文本中找到链接(a 标签),它的正则表达式模式是什么?

这种模式不起作用:

const string UrlPattern = @"(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?";
var urlMatches = Regex.Matches(text, UrlPattern);

谢谢

【问题讨论】:

  • 解析任何和所有&lt;a&gt;标签的正则表达式将是一个巨大的不可维护的黑匣子怪物。那是你想要的吗?
  • 您会考虑使用除正则表达式之外的其他解决方案,例如 HtmlAgilityPack 吗?如果是这样,您以后可能会避免很多痛苦
  • 这是一个仅包含 a 标记的文本。不是 HTML
  • @HenkHolterman 这和上面的例子完全一样。
  • Obligatory link:请链接到答案,而不是非答案。

标签: c# html regex


【解决方案1】:

我建议使用HtmlAgilityPack 来解析 HTML(可从 NuGet 获得):

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
var links = doc.DocumentNode.SelectNodes("//a[@href]")
               .Select(a => a.Attributes["href"].Value);

结果:

[
  "http://loremipsum.net/",
  "http://loremipsum.net/"
]

推荐阅读:Parsing Html The Cthulhu Way

【讨论】:

  • 我叫 samy,我同意这个答案
  • @samy 我的名字是 Sergey,谢谢你 :)
【解决方案2】:

您应该使用在此类任务中更加健壮和可靠的 XML 解析器。但是,如果您想要非常快速且非常脏的东西,这里是:

<a.*?<\/a>

如果这太简单了,你需要捕获链接地址或链接内容,那就去吧:

<a.*?href="(?<address>.*?)".*?>(?<content>.*?)<\/a>

它们都没有正确匹配嵌套标签。

【讨论】:

    【解决方案3】:

    也许是这样

    Regex regexObj = new Regex(@"<a.+?href=(['|""])(.+?)\1");
    resultString = regexObj.Match(subjectString).Groups[2].Value;
    

    匹配列表

    StringCollection resultList = new StringCollection();
    
    Regex regexObj = new Regex(@"<a.+?href=(['|""])(.+?)\1");
    Match matchResult = regexObj.Match(subjectString);
    while (matchResult.Success) {
        resultList.Add(matchResult.Groups[2].Value);
        matchResult = matchResult.NextMatch();
    } 
    

    【讨论】:

    • 你能添加更多描述吗?
    • 更改代码 - 使用正则表达式(从标签的 href 属性中选择 url)
    猜你喜欢
    • 1970-01-01
    • 2011-03-09
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    相关资源
    最近更新 更多