Question

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

Please consider case insensitivity, white-space 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>. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

Was it helpful?

Solution

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

OTHER TIPS

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.

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" } 

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.

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);
}

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top