Regular expression (C # flavor) to get the first <p> </p> after the title

I am almost done with the trackback system for my website, but I have one final rule that I just cannot get it.

What I need is an excerpt of the referenced page where I define the most relevant excerpt as:

First paragraph (tagged <p></p>

), which should be either in <h1></h1>

, <h2></h2>

or <h3></h3>

in the page HTML-source.

For example, I can successfully get the tag <title></title>

for HTML like this:

Regex reTITLE = new Regex( @"(?<=<title.*>)([\s\S]*)(?=</title>)",
RegexOptions.IgnoreCase );

Match match = reTITLE.Match( strHTMLSource );
if (match.Success)
    {
        strReferringPageTitle = match.Value.Trim( );
    }

      

My question is, what regex can I use to extract the string described in the first part of my post?

PS: I love StackOverflow and this community is a great job Joel and Co.!

0


a source to share


4 answers


Match m = Regex.Match(strHTMLSource, "^.*?</h[123]>.*?<p>(.*?)</p>",
    RegexOptions.Compiled | RegexOptions.IgnoreCase);

string para = m.Success ? m.Groups[1].Value.Trim() : string.Empty;

      



+2


a source


Personally, I would use XPath queries to make doing what you are trying to achieve much easier than messing around with regexes.



+1


a source


This regex will find all the first paragraphs after h1, h2 or h3. If you only want the first paragraph on the page, just keep the first match.

(?<=</h[1-3]>\s*?<p>)([\s\S]*?)(?=</p>)

      

You might need to configure tag mappings <p>

to account for attributes.

0


a source


There are many use cases where regex will not work as expected. For instance:

<p>foo<p>bar</p>baz</p>

<p>This paragraph is valid <!-- <p>This one isn't</p> --> </p>

      

A regex that captures the text between <p>

and </p>

will capture (respectively):

foo<p>bar

This paragraph is valid <!-- <p>This one isn't

      

If I had to process HTML found in the wild, I would use MSHTML to parse the HTML and then do a DOM search to find the objects.

Using MSHTML is not as easy as using a regular expression. But MSHTML is meant to make sense from the most messy web pages. I would rather use all of the real world messy use case knowledge he developed to handle than discover it.

See the answer to this question for a small code example.

0


a source







All Articles