Click here to Skip to main content
15,861,340 members
Articles / Programming Languages / C#
Article

StringParser

Rate me:
Please Sign up or sign in to vote.
4.92/5 (22 votes)
15 Jan 2006CPOL2 min read 145.8K   3.7K   101   50
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)


Written By
Technical Lead
Canada Canada
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, HCI 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 3 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.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Liju Sankar10-Feb-15 6:21
professionalLiju Sankar10-Feb-15 6:21 
GeneralRe: My vote of 5 Pin
Ravi Bhavnani10-Feb-15 6:29
professionalRavi Bhavnani10-Feb-15 6:29 
GeneralJust what I needed! Pin
alsamflux24-Apr-14 4:19
alsamflux24-Apr-14 4:19 
GeneralRe: Just what I needed! Pin
Ravi Bhavnani24-Apr-14 4:24
professionalRavi Bhavnani24-Apr-14 4:24 
GeneralMy vote of 5 Pin
Maciej Los31-Mar-14 6:57
mveMaciej Los31-Mar-14 6:57 
GeneralRe: My vote of 5 Pin
Ravi Bhavnani31-Mar-14 7:57
professionalRavi Bhavnani31-Mar-14 7:57 
QuestionScraping Of Data from Paginated Grid View Pin
Member 1050050624-Jan-14 18:14
professionalMember 1050050624-Jan-14 18:14 
AnswerRe: Scraping Of Data from Paginated Grid View Pin
Ravi Bhavnani24-Jan-14 19:44
professionalRavi Bhavnani24-Jan-14 19:44 
GeneralRe: Scraping Of Data from Paginated Grid View Pin
Member 1050050624-Jan-14 20:03
professionalMember 1050050624-Jan-14 20:03 
GeneralRe: Scraping Of Data from Paginated Grid View Pin
Ravi Bhavnani24-Jan-14 20:36
professionalRavi Bhavnani24-Jan-14 20:36 
GeneralRe: Scraping Of Data from Paginated Grid View Pin
Member 1050050624-Jan-14 21:58
professionalMember 1050050624-Jan-14 21:58 
QuestionCan your script be extended to a tool that can download real time quotes from google finance and store it in Amibroker Pin
Raj23230-Nov-13 21:13
Raj23230-Nov-13 21:13 
AnswerRe: Can your script be extended to a tool that can download real time quotes from google finance and store it in Amibroker Pin
Ravi Bhavnani1-Dec-13 12:16
professionalRavi Bhavnani1-Dec-13 12:16 
QuestionI am newby and need your help. Pin
Member 841644127-May-12 21:41
Member 841644127-May-12 21:41 
AnswerRe: I am newby and need your help. Pin
Ravi Bhavnani28-May-12 1:54
professionalRavi Bhavnani28-May-12 1:54 
QuestionRe: I am newby and need your help. Pin
lance.spurgeon28-May-12 8:59
lance.spurgeon28-May-12 8:59 
AnswerRe: I am newby and need your help. Pin
lance.spurgeon29-May-12 10:41
lance.spurgeon29-May-12 10:41 
GeneralMy vote of 5 Pin
samiDiab29-Feb-12 3:33
samiDiab29-Feb-12 3:33 
GeneralRe: My vote of 5 Pin
Ravi Bhavnani28-May-12 1:53
professionalRavi Bhavnani28-May-12 1:53 
GeneralExtracting Meta Keywords and Descriptions Pin
keith_fra26-Jul-07 9:48
keith_fra26-Jul-07 9:48 
Hi, this is really good stuff!

Any thoughts on the best way to extract out just the meta keywords and descriptions?

I have stuck on this for about a week and then I came across your site.

I already have the HTML String I was just wondering the best way to get those elements out.

Thanks!
QuestionRewindTo? Pin
krn_2k19-Jun-07 8:23
krn_2k19-Jun-07 8:23 
AnswerRe: RewindTo? Pin
Ravi Bhavnani19-Jun-07 8:37
professionalRavi Bhavnani19-Jun-07 8:37 
GeneralRe: RewindTo? Pin
krn_2k19-Jun-07 8:44
krn_2k19-Jun-07 8:44 
Generalextract tags Pin
rama jayapal29-Mar-07 21:50
rama jayapal29-Mar-07 21:50 
GeneralRe: extract tags Pin
Ravi Bhavnani30-Mar-07 2:58
professionalRavi Bhavnani30-Mar-07 2:58 

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

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