Link to home
Start Free TrialLog in
Avatar of supergirl2008
supergirl2008

asked on

regEx for pulling out google links

i want to use code like this to pull all 10 links per Google result page. i am doing this in a c# web app but it may turn into console or desktop app.


i am getting the content like this:
WebClient w = new WebClient();
string pageSource = w.DownloadString(http://www.google.com/search?hl=en&q=weather&start=0)

then i wanted to be able to use regEx to extract all top level url links.

any ideas? or ideas on how to retrieve urls from Google results?

thoughts?
Avatar of Ravi Vaddadi
Ravi Vaddadi
Flag of United States of America image

WebClient w = new WebClient();
            string pageSource = w.DownloadString("http://www.google.com/search?hl=en&q=weather&start=0");
            Regex reg = new Regex("<a[^>]*>.*?</a>");
            StringBuilder sb = new StringBuilder();
            foreach(Match m in reg.Matches(pageSource))
            {
                sb.AppendLine(m.Value);
            }
Check this out to get an idea.

http://stackoverflow.com/questions/369147/javascript-regex-to-extract-anchor-text-and-url-from-anchor-tags

http://www.askaboutphp.com/25/regex-extract-content.html

The links above are in javascript and PHP but you can use the pattern/s to incorporate in a System.Text.RegularExpressions.Regex function in C#.


ASKER CERTIFIED SOLUTION
Avatar of shadow77
shadow77

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of supergirl2008
supergirl2008

ASKER

shadow77:how can i learn to be a super regex master like you?
shadow77:how can i learn to be a super regex master like you?
Thanks for the kind words.  Jan Goyvaerts, who really is a super regex master, has an excellent free web site full of great info and tutorials (http://www.regular-expressions.info/).  He also has an excellent product, Regex Buddy ($39.95, http://www.regular-expressions.info/regexbuddy.html), that lets you test expressions.  It explains any RegEx as you build it and provides test tools and it supports several RegEx dialects (.NET, JavaScript, Perl, etc)

Regarding the specific problem you posed originally, I looked through the HTML to see what distinguished the links you wanted from all the others (in this case,

).  The (?<=...) subexpression excludes any matches that do not follow the pattern that replaces ...  It's called a lookbehind; there's also lookahead; and both can be positive (subexpression must appear) or negative (subexpression must not appear).

There are also lots of good people who post in the Regular Expressions zone on this site.