当正则表达式在.NET处理我有两个选择:正则表达式:匹配和捕获.NET中的一个模式
检查字符串模式匹配:
<a ([^>]*?)href=\"http://the.site.com/photo/[0-9]*\">
捕获属于部分图案:
<a ([^>]*?)href=\"http://the.site.com/photo/(?<photoname>.*?)\">
但是如果我想检查模式匹配并捕获与单个RegEx相匹配的部分,该怎么办?
当正则表达式在.NET处理我有两个选择:正则表达式:匹配和捕获.NET中的一个模式
检查字符串模式匹配:
<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 [email protected]"^(?<=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
元素的第一个属性,该正则表达式仍然可以工作。它也会忽略任意空间。
如果它不匹配,它将如何捕获它? Lookaheads/lookbehinds用于捕获部分匹配 – Jonesopolis
@Jonesy:'(?。*?)'将捕获任何字符序列,但我只需要[0-9] *'。 –
Paul
@Paul - 你为什么用'。*'替换'[0-9] *'? – BeemerGuy