C#正则表达式提取div的内容

Bar*_*ink 6 c# regex

我已经看到了我的一些相关问题,我尝试了它们但是它们不起作用.我想匹配div中的内容和id"thumbs".但是regex.Success返回false :(

Match regex = Regex.Match(html, @"<div[^>]*id=""thumbs"">(.+?)</div>");
Run Code Online (Sandbox Code Playgroud)

Ani*_*dha 8

正则表达式不是解析HTML文件的好选择.

HTML格式不严格,格式也不规则.

使用htmlagilitypack


为什么要使用解析器?

考虑你的正则表达式.有无数种情况你可以破坏你的代码

  • 如果有嵌套的 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
Run Code Online (Sandbox Code Playgroud)