Regex Extract html Body

15,707

Solution 1

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.

Solution 2

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;
        }
Share:
15,707
Bruce Adams
Author by

Bruce Adams

...

Updated on June 15, 2022

Comments

  • Bruce Adams
    Bruce Adams about 2 years

    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?

  • Saif Khan
    Saif Khan about 15 years
    I agree. I've used this and must say it's fast, neat and clean.
  • Darryl
    Darryl about 13 years
    Thank you! That's what I strive for.
  • Thomas Amar
    Thomas Amar over 11 years
    Great, that does exactly what I needed.
  • Lightweight
    Lightweight over 10 years
    Thanks for answering the question!
  • Quango
    Quango over 10 years
    A good simple solution, but beware of body tags with spaces or attributes: < body id='content'> would not match
  • ShaileshDev
    ShaileshDev over 7 years
    Please provide detail solution.