tags:

views:

1657

answers:

6

C#: What is a good Regex to parse hyperlinks and their description?

Please consider case insensitivity, whitespace and use of single quotes (instead of double quotes) around the HREF tag.

Please also consider obtaining hyperlinks which have other tags within the <a> tags such as <b> and <i>

+1  A: 

I found this but apparently these guys had some problems with it.

Edit: (It works!)
I have now done my own testing and found that it works, I don't know C# so I can't give you a C# answer but I do know PHP and here's the matches array I got back from running it on this:

<a href="pages/index.php" title="the title">Text</a>

array(3) { [0]=> string(52) "Text" [1]=> string(15) "pages/index.php" [2]=> string(4) "Text" }
Teifion
+4  A: 

As long as there are no nested tags (and no line breaks), the following variant works well:

<a\s+href=(?:"([^"]+)"|'([^']+)').*?>(.*?)</a>

As soon as nested tags come into play, regular expressions are unfit for parsing. However, you can still use them by applying more advanced features of modern interpreters (depending on your regex machine). E.g. .NET regular expressions use a stack; I found this:

(?:<a.*?href=[""'](?<url>.*?)[""'].*?>)(?<name>(?><a[^<]*>(?<DEPTH>)|</a>(?<-DEPTH>)|.)+)(?(DEPTH)(?!))(?:</a>)

Source: http://weblogs.asp.net/scottcate/archive/2004/12/13/281955.aspx

Konrad Rudolph
+1  A: 

I have a regex that handles most cases, though I believe it does match HTML within a multiline comment.

It's written using the .NET syntax, but should be easily translatable.

Haacked
+3  A: 

See this example from StackOverflow: Regular expression for parsing links from a webpage?

Using The HTML Agility Pack you can parse the html, and extract details using the semantics of the HTML, instead of a broken regex.

Jerub
Exactly - regular expressions are great, but using them on HTML or XML is a recipe for pain.
slim
+1 for HTML Agility Pack. Someone suggested this to me recently and it worked wonderfully.
Mark
A: 

Just going to throw this snippet out there now that I have it working..this is a less greedy version of one suggested earlier. The original wouldnt work if the input had multiple hyperlinks. This code below will allow you to loop through all the hyperlinks:

static Regex rHref = new Regex(@"<a.*?href=[""'](?<url>[^""^']+[.]*?)[""'].*?>(?<keywords>[^<]+[.]*?)</a>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
public void ParseHyperlinks(string html)
{
   MatchCollection mcHref = rHref.Matches(html);

   foreach (Match m in mcHref)
      AddKeywordLink(m.Groups["keywords"].Value, m.Groups["url"].Value);
}
James Shaw
A: 

Here is a regular expression that will match the balanced tags.

(?:.*?">""'[""'].*?>)(?(?>(?)|(?<-DEPTH>)|.)+)(?(DEPTH)(?!))(?:)

Svarga