使用正则表达式从 HTML 中提取文本和链接
我想从 html 文档中提取文本,并将链接保留在其中。例如:
从这个 HTML 代码中
<div class="CssClass21">bla1 bla1 bla1 <a href="http://www.ibrii.com">go to ibrii</a> bla2 bla2 bla2 <img src="http://www.contoso.com/hello.jpg"> <span class="cssClass34">hello hello</span>
,我想提取这个
bla1 bla1 bla1 <a href="http://www.ibrii.com">go to ibrii</a> bla2 bla2 bla2 hello hello
在 StackOverflow 上的另一篇文章中,我找到了 RegEx <[^>]*>
,它允许通过替换每个匹配来提取文本什么也没有。如何从匹配中排除锚标记?看来正则表达式不允许反向匹配。
I would like to extract text from an html document keeping the links inside it. for example:
From this HTML code
<div class="CssClass21">bla1 bla1 bla1 <a href="http://www.ibrii.com">go to ibrii</a> bla2 bla2 bla2 <img src="http://www.contoso.com/hello.jpg"> <span class="cssClass34">hello hello</span>
I would like to extract just this
bla1 bla1 bla1 <a href="http://www.ibrii.com">go to ibrii</a> bla2 bla2 bla2 hello hello
In another post on StackOverflow i have found the RegEx <[^>]*>
which allows to extract text by replacing every match with nothing. How can I exclude the anchor tags from the match? It seems that RegEx do not allow inverse matching.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
暂时将
...
编码为其他内容,删除所有其他标签,然后恢复标签:
在上面的代码中,我使用 NUL 和 SOH 字符(ASCII 0x00 和 0x01)作为
标记的替换,只是因为它们不太可能出现在字符串中。请随意将它们替换为不会出现在字符串中的任何其他字符或字符序列。
从其他评论来看,您似乎正在浏览器中操作。在这种情况下,浏览器已经为您将 HTML 解析为漂亮的 DOM 树。使用 DOM 方法解析树并按照您想要的方式处理它:
Temporarily encode
<a href ...>...</a>
into something else, remove all other tags then restore the<a>
tags:In the code above I use the NUL and SOH characters (ASCII 0x00 and 0x01) as replacements for
<a>
tags simply because it is highly unlikely that they would appear in strings. Feel free to replace them with any other character or sequence of characters that would not appear in your string.From additional comments it appears you're operating in a browser. In which case the browser has already parsed the HTML for you into a nice DOM tree. Use DOM methods to parse through the tree and process it the way you want:
正则表达式确实允许通过 lookahead 进行非平凡的否定形式,但在这种情况下作为一个练习是很好的,因为虽然我不是每次 regexp 与 HTML 一起提及时都会热血沸腾的狂热分子,但这确实是一个需要用解析器解决的问题。
Regular expressions do allow a non-trivial form of negation through lookahead but in this case it would be just good as an excercise because, while I'n no zealot that burns with holy fire every time regexp get mentioned together with HTML, this is really a problem to be solved with a parser.