Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Extract html Body

Tags:

c#

regex

vb.net

How would I use Regex to extract the body from a html doc, taking into account that the html and body tags might be in uppercase, lowercase or might not exist?

like image 946
Bruce Adams Avatar asked Jun 11 '09 17:06

Bruce Adams


2 Answers

How about something like this?

It captures everything between <body></body> tags (case insensitive due to RegexOptions.IgnoreCase) into a group named theBody.

RegexOptions.Singleline allows us to handle multiline HTML as a single string.

If the HTML does not contain <body></body> tags, the Success property of the match will be false.

        string html;

        // Populate the html string here

        RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Singleline;
        Regex regx = new Regex( "<body>(?<theBody>.*)</body>", options );

        Match match = regx.Match( html );

        if ( match.Success ) {
            string theBody = match.Groups["theBody"].Value;
        }
like image 66
Darryl Avatar answered Oct 15 '22 10:10

Darryl


Don't use a regular expression for this - use something like the Html Agility Pack.

This is an agile HTML parser that builds a read/write DOM and supports plain XPATH or XSLT (you actually don't HAVE to understand XPATH nor XSLT to use it, don't worry...). It is a .NET code library that allows you to parse "out of the web" HTML files. The parser is very tolerant with "real world" malformed HTML. The object model is very similar to what proposes System.Xml, but for HTML documents (or streams).

Then you can extract the body with an XPATH.

like image 40
Andrew Hare Avatar answered Oct 15 '22 11:10

Andrew Hare