0

想从锚标签获取href链接。我在用

regex = @"<a[^>]*?href\s*=3D\s*[""']?    ([^'"" >]+?)[ '""][^>]*?>". 

如果 href 在单行中,我可以成功,但在以下情况下失败

Text = <a target=3D"_blank" hr=
ef=3D"http://abc.com/blog/check-your-cars-health-before-going-on-lo=
ng-trip/">

正在读取的文件是 eml 文件而不是 html 文件请为上述建议正确的正则表达式

4

2 回答 2

2

您不应该真正尝试使用正则表达式解析 HTML,就是原因。您可以查看一个健壮的 HTML 处理库,例如HTML Agility Pack

This previous SO post可能有一些与您正在做的事情类似的事情。

于 2013-07-15T13:23:06.290 回答
0

描述

这个正则表达式将:

  • 在锚标签内找到 href 属性值
  • 避免一些困难的边缘情况

<a\b(?=\s)(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?\shr=.*?ef=3D['"]([^"]*)['"]?)(?:[^>=]|='[^']*'|="[^"]*"|=[^'"\s]*)*"\s?\/?>.*?<\/a>

在此处输入图像描述

例子

示例文本

注意 onmouseover 中的困难边缘情况

<a onmouseover=' href="NotTheHrefYoureLookingFor" ; funRotator(href) ; ' target=3D"_blank" href="http://abc.com/blog/check-your-cars-health-before-going-on-lo= ng-trip/">link text </a>

捕获组

[0] => <a onmouseover=' href=" hr=
ef=3D NotTheHrefYoureLookingFor" ; funRotator(href) ; ' target=3D"_blank" hr=
ef=3D"http://abc.com/blog/check-your-cars-health-before-going-on-lo=
ng-trip/">link text
</a>
[1] => http://abc.com/blog/check-your-cars-health-before-going-on-lo=
ng-trip/
于 2013-07-15T13:57:24.667 回答