开发者

How to parse html and return array of values in c# using regex.split

Currently I'm trying to parse some html and return an array with the values inside开发者_C百科 each element.

For example:

if I pass the below markup into a function

var element = "td";
var html = "<tr><td>1</td><td>2</td></tr>";
return Regex.Split(html, string.Format("<{0}*.>(.*?)</{0}>", element));

And I'm expecting back an array[] { 1, 2 }

What does my regex need to look like? Currently my array is coming back with far to many elements and my regex skills are lacking


Do not parse HTML using regular expressions.

Instead, you should use the HTML Agility Pack.

For example:

HtmlDocument doc = new HtmlDocument();
doc.Parse(str);

IEnumerable<string> cells = doc.DocumentNode.Descendants("td").Select(td => td.InnerText);


You really should not use regex to parse html. html is not a regular language, so regex isn't capable of interpreting it properly. You should use a parser.

c# has html parsers for this.


The method to load the html has changed since the original answer, it is now:

// From File
var doc = new HtmlDocument();
doc.Load(filePath);

// From String
var doc = new HtmlDocument();
doc.LoadHtml(html);

// From Web
var url = "http://html-agility-pack.net/";
var web = new HtmlWeb();
var doc = web.Load(url);

However if you follow the documentation as per the provided link above you should be fine :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜