Paragraph HTML Regex. HTML pages have paragraphs in them. We can match these with Regex. This is useful for extracting summaries from many pages or articles.
C# method info. This simple method extracts and matches the first paragraph element in an HTML document. This function uses the regular expression library included in the .NET Framework.
Example. We scan an entire HTML file and extract text in between a paragraph opening tag and closing tag. You can put this method, GetFirstParagraph, in a utility class.
Detail This uses the static Regex.Match method declared in the System.Text.RegularExpressions namespace.
Info The Regex looks for brackets with the letter "p" in between them. It then skips zero or more whitespace characters inside those tags.
Finally It captures the minimum number of characters between the start tag and end tag. Both tags must be found for the match to proceed.
using System;
using System.IO;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
// Read in an HTML file.
string html = File.ReadAllText("Problem.html");
// Get the first paragraph.
Console.Write(GetFirstParagraph(html));
}
/// <summary>
/// Get first paragraph between P tags.
/// </summary>
static string GetFirstParagraph(string file)
{
Match m = Regex.Match(file, @"<p>\s*(.+?)\s*</p>");
if (m.Success)
{
return m.Groups[1].Value;
}
else
{
return "";
}
}
}This is the first paragraph...
A discussion. Understanding regular expressions can be difficult, but this one is fairly simple. The method is not flexible. It is hard to parse HTML correctly all the time without an HTML parser.
Summary. We looked at how you can match the paragraph element in your HTML files. This is useful code that I run several times a day, and it functions correctly.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 25, 2022 (edit).