Click here to Skip to main content
Licence CPOL
First Posted 15 Jan 2006
Views 73,940
Bookmarked 93 times

StringParser

By | 15 Jan 2006 | Article
An object that makes it easy to extract information from strings, especially HTML content.

Introduction

StringParser is an object that helps you extract information from a string.  The class is perhaps best suited to parse HTML pages downloaded from the web (see my WebResourceProvider class that helps you do this).  You use StringParser by constructing it with some content (i.e. a string) and using its navigational and extraction methods to extract substrings from the content.  StringParser also provides some static methods designed specifically for parsing HTML.

API

Here are some of the methods provided by StringParser.  Please see the accompanying documentation for an exhaustive list.

Navigational API
resetPosition()
skipToEndOf()
skipToEndOfNoCase()
skipToStartOf()
skipToStartOfNoCase()
  Extraction API
extractTo()
extractToNoCase()
extractUntil()
extractUntilNoCase()
extractToEnd()
  Position query API
at()
atNoCase()
  HTML parsing API
getLinks()
removeComments()
removeEnclosingAnchorTag()
removeEnclosingQuotes()
removeHtml()
removeScripts()

Example 1 - Extracting delimited text

This example shows how to extract text contained between two delimiters. 
  // Extract text between the comma and question mark
  string strExtract = "";
  string str = "Hello Sally, how are you?";
  StringParser p = new StringParser (str);
  if (p.skipToStartOf (",") && p.extractTo ("?", ref strExtract))
     Console.Writeln ("Extracted text = {0}", strExtract);
  else
     Console.Writeln ("No text extracted.");

Example 2 - Extracting the nth occurence of a delimited string

This example shows how to obtain the href attribute of the third anchor tag (<a>) in an HTML string.  The example assumes the string contains valid HTML.
  // Get href attribute of 3rd <a> tag
  string strExtract = "";
  string str = "..."; // HTML
  StringParser p = new StringParser (str);
  if (p.skipToStartOfNoCase ("<a") &&
      p.skipToStartOfNoCase ("<a") &&
      p.skipToStartOfNoCase ("<a") &&
      p.skipToStartOfNoCase ("href=\"") &&
      p.extractTo ("\"", ref strExtract))
     Console.Writeln ("Extracted text = {0}", strExtract);
  else
     Console.Writeln ("No text extracted.");

Example 3 - Global case-insensitive replacement

This example shows how to case-insensitively replace a string in the parser's content..
  // Replace every occurence of <td> with <td class="foo">
  string str = "..."; // HTML
  StringParser p = new StringParser (str);
  p.replaceEvery ("<td>", "<td class=\"foo\">");

Example 4 - Poor man's web scraping

This example shows how to obtain a stock's quote from the content downloaded from Yahoo Finance (MSFT).  The example makes assumptions about the format of the web page.
  // Scrape http://finance.yahoo.com/q?s=msft
  string strQuote = "";
  string str = "..."; // HTML downloaded from http://finance.yahoo.com/q?s=msft
  StringParser p = new StringParser (str);
  if (p.skipToEndOfNoCase ("Last Trade:</td><td class="yfnc_tabledata1"><big><b>") &&
      p.extractTo ("</b>", ref strQuote))
     Console.Writeln ("MSFT (delayed) = {0}", strQuote);

Example 5 - Get list of hyperlinked phrases

This example shows how to obtain the list of hyperlinked phrases in HTML content.
  ArrayList phrases = new ArrayList();
  string str = "..."; // HTML content
  StringParser p = new StringParser (str);
  while (p.skipToStartOfNoCase ("<a")) {
    string strPhrase = "";
    if (p.skipToEndOf (">") && p.extractTo ("<a>", ref strPhrase))
       phrases.Add (strPhrase);
  }

Demo applications

C# applications (with full source code) that use StringParser can be found here:

Revision History

  • 15 Jan 2006
    Initial version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Ravi Bhavnani



Canada Canada

Member

Ravi Bhavnani is an ardent fan of Microsoft technologies who loves building Windows apps, especially PIMs, system utilities, and things that go bump on the Internet. During his career, Ravi has developed expert systems, desktop imaging apps, marketing automation software, EDA tools, a platform to help people find, analyze and understand information, trading software for institutional investors and advanced data visualization solutions. He currently works for a company that provides enterprise workforce management solutions to large clients.
 
His interests include the .NET framework, reasoning systems, financial analysis and algorithmic trading, NLP, CHI and UI design. Ravi holds a BS in Physics and Math and an MS in Computer Science and was a Microsoft MVP (C++ and C# in 2006 and 2007). He is also the co-inventor of 2 patents on software security and generating data visualization dashboards. His claim to fame is that he crafted CodeProject's "joke" forum post icon.
 
Ravi's biggest fear is that one day he might actually get a life, although the chances of that happening seem extremely remote.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 PinmembersamiDiab3:33 29 Feb '12  
GeneralExtracting Meta Keywords and Descriptions Pinmemberkeith_fra9:48 26 Jul '07  
QuestionRewindTo? Pinmemberkrn_2k8:23 19 Jun '07  
AnswerRe: RewindTo? PinmemberRavi Bhavnani8:37 19 Jun '07  
GeneralRe: RewindTo? Pinmemberkrn_2k8:44 19 Jun '07  
Generalextract tags Pinmemberrama jayapal21:50 29 Mar '07  
GeneralRe: extract tags PinmemberRavi Bhavnani2:58 30 Mar '07  
Generalgood stuff Pinmembertonyc2a6:34 25 Feb '07  
GeneralRe: good stuff PinmemberRavi Bhavnani6:42 25 Feb '07  
QuestionString parser for Client server Pinmembervenkiiz3:23 23 Jan '07  
AnswerRe: String parser for Client server PinmemberRavi Bhavnani4:40 23 Jan '07  
GeneralC++ Version PinmemberImtiaz Murtaza20:18 23 Nov '06  
AnswerRe: C++ Version PinmemberRavi Bhavnani1:57 24 Nov '06  
Questionthe best articale!!! Pinmemberronicohen7:51 17 Nov '06  
AnswerRe: the best articale!!! PinmemberRavi Bhavnani7:59 17 Nov '06  
GeneralThis is awesome! Pinmemberzythra17:49 15 Apr '06  
GeneralRe: This is awesome! PinmemberRavi Bhavnani4:56 16 Apr '06  
QuestionHow to keep session on Pinmembersumoncsekugmail0:57 19 Feb '06  
AnswerRe: How to keep session on PinmemberRavi Bhavnani2:28 19 Feb '06  
GeneralReading Meta tags Pinmemberrizwan_rashid18:26 14 Feb '06  
GeneralRe: Reading Meta tags PinmemberRavi Bhavnani2:44 15 Feb '06  
GeneralHELP!! Pinmemberrizwan_rashid6:15 14 Feb '06  
GeneralHELP!!!! Pinmemberrizwan_rashid0:44 12 Feb '06  
GeneralRe: HELP!!!! PinmemberRavi Bhavnani1:14 12 Feb '06  
GeneralRe: HELP!!!! Pinmemberrizwan_rashid1:38 12 Feb '06  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 15 Jan 2006
Article Copyright 2006 by Ravi Bhavnani
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid