Skip to content Skip to sidebar Skip to footer

Regex To Parse Hyperlinks And Descriptions

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 H

Solution 1:

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

Solution 2:

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.

Solution 3:

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

Solution 4:

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.

Solution 5:

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);
publicvoidParseHyperlinks(string html)
{
   MatchCollection mcHref = rHref.Matches(html);

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

Post a Comment for "Regex To Parse Hyperlinks And Descriptions"