Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to Parse Hyperlinks and Descriptions

Tags:

html

regex

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>. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

like image 329
Krishna Kumar Avatar asked Dec 31 '22 11:12

Krishna Kumar


2 Answers

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

like image 104
Konrad Rudolph Avatar answered Jan 15 '23 00:01

Konrad Rudolph


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.

like image 33
Jerub Avatar answered Jan 14 '23 23:01

Jerub