【问题标题】:Matching href any string between two known strings匹配两个已知字符串之间的href任何字符串
【发布时间】:2014-10-09 07:09:30
【问题描述】:

我正在尝试匹配 html 页面中的多个 href,但似乎无法正常工作。当我使用我的正则表达式时,我没有得到任何匹配。如何获得整个 href 的多个匹配项,将它们分成两个指定的组?

要匹配的多个 href 示例:

<a href="/string1/any string here/string2">text here</a>

我的正则表达式代码:

MatchCollection m1 = Regex.Matches(result, @"<a\shref=""(?<url>(\/string1\/).*?(\/string2))"">(?<text>.*?)</a>", RegexOptions.Singleline);

这可行,但除了我需要的之外,还匹配我不感兴趣的href:

MatchCollection m1 = Regex.Matches(result, @"<a\shref=""(?<url>(\/string1\/).*?)"">(?<text>.*?)</a>", RegexOptions.Singleline);

【问题讨论】:

  • 所以你需要any string here
  • 您的问题是什么?太好了,您有一些正则表达式,但是您的代码在哪里?显示预期的行为/输出和实际的行为/输出。
  • 抱歉,第一次使用stackoverflow。我编辑了我的问题。

标签: c# regex href


【解决方案1】:

使用Parentheses for Grouping and Capturing

<a href="(\/string1\/)(.*?)(\/string2)">

这里是regex101 demo


或者试试Character Classes or Character Sets

<a href="(\/string1\/)([^\/]+)(\/string2)">

我不知道您为什么需要您已经知道的 string1string2。您只需要介于两者之间的任何字符串

尝试不捕获组。

阅读更多关于Lookahead and Lookbehind Zero-Length Assertions

(?<=<a href="\/string1\/)[^\/]*(?=\/string2">)

Online demo

【讨论】:

  • 我试图保持简单,以便返回给我的所有匹配项看起来像:“/string1/anystring1/string2”、“string1/anystring2/string2”等
  • 谢谢,这个成功了:
【解决方案2】:

如 cmets 中所述,使用真正的 html 解析器,如 HtmlAgilityPack,而不是 Regex

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(@"<a href=""/string1/any string here/string2"">text here</a>");

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

或者没有 xpath

var links = doc.DocumentNode
                .Descendants("a")
                .Where(a=>a.Attributes["href"]!=null)
                .Select(a=>a.Attributes["href"].Value)
                .ToList();

【讨论】:

  • 谢谢,我也试试看。
  • 哇,这很简单,我可以看到长期使用 html 解析器可能更安全。我能够添加一些 LINQ 过滤器来缩小我需要的范围。
猜你喜欢
  • 1970-01-01
  • 2013-07-25
  • 1970-01-01
  • 2011-01-30
  • 2020-11-13
  • 1970-01-01
  • 2018-07-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多