-2

在 .NET 中处理 RegEx 时,我有两个选择:

  1. 检查字符串的模式匹配:

    <a ([^>]*?)href=\"http://the.site.com/photo/[0-9]*\">

  2. 捕获模式的一部分:

    <a ([^>]*?)href=\"http://the.site.com/photo/(?<photoname>.*?)\">

但是,如果我想检查模式匹配并捕获与单个 RegEx 匹配的部分怎么办?

4

3 回答 3

2

捕获时只需使用它:

<a ([^>]*?)href=\"http://the.site.com/photo/(?<photoname>[0-9]+)\">
于 2013-10-29T14:39:11.540 回答
1

使用htmlAgilityPack

HtmlDocument doc = new HtmlDocument();
doc.Load(htmlUrl);

var pattern=@"^(?<=https?://the.site.com/photo/)\d+$";
var hrefList= doc.DocumentNode
                 .SelectNodes("//a[@href]")
                 .Select(p =>p.Attributes["href"].Value)//select all hrefs
                 .Where(p => Regex.IsMatch(p,pattern))//filter href
                 .Select(p=>Regex.Match(p,pattern).Value);//select required digits
于 2013-10-29T14:32:27.740 回答
0

好先生,您可以用一个模式匹配并捕获到一个命名组中!

<a (?:[^>]*?)href\s*?=\s*\"http://the.site.com/photo/(?<photoname>[0-9]+)\"

命名的组photoname将包含您想要的捕获。

即使href不是a元素的第一个属性,此正则表达式也将起作用。它还将忽略任意空格。

于 2013-10-29T14:46:52.017 回答