正则表达式来解析超链接和描述 [英] Regex to Parse Hyperlinks and Descriptions

查看:201
本文介绍了正则表达式来解析超链接和描述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑不区分大小写,空白和使用单引号(而不是双引号),请考虑大小写不敏感,空白和使用单引号(而不是双引号) )

请考虑获取在< a> 标签中包含其他标签的超链接例如< b> < i>

解决方案

只要没有嵌套标签(并且没有换行符)

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

一旦嵌套标签发挥作用,正则表达式不适合解析,但是仍然可以通过应用更高级的现代解释器功能来使用它们(具体取决于您的正则表达式),例如.NET正则表达式使用堆栈;我发现这个:

 (?:< a。*?href = ['''](?< url>。* ??) '] * GT)(小于名称>(大于;<一个[^<] *>(小于DEPTH>有?)|< / A>(小于? ; -DEPTH>)。。)+)(?(DEPTH)(?!))(?:)

资料来源: http:// weblogs .asp.net / scottcate /存档/ 2004/12 /二十八万一千九百五十五分之一十三.aspx


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

解决方案

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

这篇关于正则表达式来解析超链接和描述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆