我看过我的一些相关问题,我试过了,但没有用。 我想将一个 div 中的内容与 ID 为“thumbs”的内容相匹配。但是 regex.Success 返回 false :(
Match regex = Regex.Match(html, @"<div[^>]*id=""thumbs"">(.+?)</div>");
最佳答案
正则表达式不是解析 HTML 文件的好选择..
HTML 不严格,格式也不规则..
为什么要使用解析器?
考虑你的正则表达式..有无数种情况下你可以破坏你的代码
- 如果有嵌套 div,您的正则表达式将不起作用
- 有些 div 没有结束标记!(XHTML 除外)
您可以使用此代码通过 HtmlAgilityPack
检索它
HtmlDocument doc = new HtmlDocument();
doc.Load(yourStream);
var itemList = doc.DocumentNode.SelectNodes("//div[@id='thumbs']")//this xpath selects all div with thubs id
.Select(p => p.InnerText)
.ToList();
//itemList now contain all the div tags content having its id as thumbs
关于C#正则表达式提取一个div的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17470525/