Showing posts with label RegEx. Show all posts
Showing posts with label RegEx. Show all posts

Parse HTML Table with RegEx in .NET

This is used to parse an html table. Practical to obtain results from a web page, formatted in a table.

The algorithm requires to know the number of colums to parse. Then, using regex, it loops in all the lines of the tables, and the content of each column of theeese line is inside the m.Groups[index].Value.


public void ParseHtmlTable(string html)
{

/// Basic html table pattern
string columnPattern = @"\<TD[^\>]*\>([^\<]*)\<\/TD\>";
string betweenColumnsPattern = @"[^\<]*";


/// Construct the global pattern for a given nomber of columns
int nbColums = 11;

StringBuilder sbPattern = new StringBuilder();
for (int i = 0; i < nbColums; i++)
{
sbPattern.Append(columnPattern);
sbPattern.Append(betweenColumnsPattern);
}
sbPattern.Append(columnPattern);

/// Parse the result
Regex r = new Regex(sbPattern.ToString(), RegexOptions.IgnoreCase);

foreach (Match m in r.Matches(html))
{
// example
string insideCell1 = m.Groups[0].Value;
string insideCell2 = m.Groups[2].Value;

/// do things..


}
}