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.!
a source to share
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.
a source to share