HTML pages have paragraphs in them. In a C# program, we can match these paragraphs with Regex
. This is useful for extracting summaries from many pages or articles.
This simple method extracts and matches the first paragraph element in an HTML document. This function uses the regular expression library included in .NET.
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
.
string
literal. Then we pass this string
to the GetFirstParagraph
method.GetFirstParagraph()
uses the static
Regex.Match
method declared in the System.Text.RegularExpressions
namespace.Regex
looks for brackets with the letter "p" in between them. It then skips zero or more whitespace characters inside those tags.Regex
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.Text.RegularExpressions; class Program { static void Main() { // Step 1: call method with html text. string html = "<html><title>...</title><body><p>Result.</p></body></html>"; Console.WriteLine(GetFirstParagraph(html)); } /// <summary> /// Get first paragraph between P tags. /// </summary> static string GetFirstParagraph(string file) { // Step 2: use Regex to match a paragraph. Match match = Regex.Match(file, @"<p>\s*(.+?)\s*</p>"); if (match.Success) { return match.Groups[1].Value; } else { return ""; } } }Result.
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.
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.