在 .NET 中处理 RegEx 时,我有两个选择:
检查字符串的模式匹配:
<a ([^>]*?)href=\"http://the.site.com/photo/[0-9]*\">
捕获模式的一部分:
<a ([^>]*?)href=\"http://the.site.com/photo/(?<photoname>.*?)\">
但是,如果我想检查模式匹配并捕获与单个 RegEx 匹配的部分怎么办?
捕获时只需使用它:
<a ([^>]*?)href=\"http://the.site.com/photo/(?<photoname>[0-9]+)\">
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
好先生,您可以用一个模式匹配并捕获到一个命名组中!
<a (?:[^>]*?)href\s*?=\s*\"http://the.site.com/photo/(?<photoname>[0-9]+)\"
命名的组photoname
将包含您想要的捕获。
即使href
不是a
元素的第一个属性,此正则表达式也将起作用。它还将忽略任意空格。