Solved

Advanced C# string parse to pull specific string and substrings out of a larger string.

Posted on 2008-10-27
3
1,927 Views
Last Modified: 2013-12-17
I have a C# string that represents HTML code.  I need to parse the string and find each instance of the img element.  Once the img element is taken out, I need to then extract the src attribute from the img element.  

Example if I have the C# string, I need to find <img src="http://www.someurl.com/image1.gif" /> and assign it to a string.  Then I need to parse the new string for the src http://www.someurl.com/image1.gif.  I am somewhat familar with C# string functions, but I am not sure how to begin working on this.

If you need more clarification please let me know.  Thank you for your help.
0
Comment
Question by:shanemay
3 Comments
 
LVL 9

Accepted Solution

by:
gdupadhyay earned 500 total points
ID: 22816337
You can do it by regural expression easily.
Add

using System.IO;
using System.Text;
using System.Text.RegularExpressions;

Now in function you have to write following:
// File Path.
string filename = "C:\\test\\Test.txt";

string pattern = @"<img .* />";

FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(file);
string strFileText;
strFileText = sr.ReadToEnd();
Regex re = new Regex(pattern1);
MatchCollection mc = re.Matches(strFileText);


int mIdx = 0;
string strTemp1;
string strTemp2;
foreach (Match m in mc)
{
string strTemp = m.ToString();
strTemp1 = strTemp.Replace("<img src=", "");
strTemp2 = strTemp1.Replace(" />", "");
}

The final string strTemp2 is "http://www.someurl.com/image1.gif".

I have tested this code and working fine.

Please let me know, if you have any question.

Good Luck

 
0
 

Author Closing Comment

by:shanemay
ID: 31510481
Thank you so much for the quick response.  I really appreciate the crystal clear code example.  This is exactly what I needed,  I did not think I would have this working today.  Again, thank you so much.  
0
 
LVL 8

Expert Comment

by:mkosbie
ID: 22816810
RegEx's are definitely the way to go, but the code provided is pretty cumbersome.  It won't match any img tag with more than a src attribute (eg <img src="img.jpg" id="img1">, and it does a lot of extra processing. You can extract everything you need in one pass with a function like this (this returns the sources in an arraylist):
    private ArrayList getImageSources(String HTML)

    {

        Regex re = new Regex("<img\\s[^>]*?src=[\"']([^\"']+)[\"'][^>]*>", RegexOptions.IgnoreCase);

        MatchCollection matches = re.Matches(HTML);
 

        ArrayList sources = new ArrayList();

        foreach (Match m in matches) {

            sources.Add(m.Groups[1]);

        }
 

        return sources;

    }

Open in new window

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Both in life and business – not all partnerships are created equal. As the demand for cloud services increases, so do the number of self-proclaimed cloud partners. Asking the right questions up front in the partnership, will enable both parties …

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now