Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
353 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

<as+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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...