用正则表达式选择HTML文本元素?

tar*_*ani 5 javascript regex jquery text-extraction html-parsing

我想©在HTML文档中查找,并且基本上获得版权所属的实体.

版权线显示了几种不同的方式:

<p class="bg-copy">&copy; 2011  The New York Times Company</p>
Run Code Online (Sandbox Code Playgroud)

要么

<a href="http://www.nytimes.com/ref/membercenter/help/copyright.html">
&copy; 2011</a> 
<a href="http://www.nytco.com/">The New York Times Company</a>
Run Code Online (Sandbox Code Playgroud)

要么

<br>Published since 1996<br>Copyright &copy; CounterPunch<br>
All rights reserved.<br>
Run Code Online (Sandbox Code Playgroud)

我想忽略日期和干预标签,只是得到"纽约时报公司"或"反击".

我还没有找到很多关于使用JavaScript或JQuery的正则表达式,但我得到的印象是它可能导致严重的问题.如果有更好的方法,请告诉我.

mor*_*rja 2

对于一个强大的解决方案,您可能需要 DOM 导航和一些启发式方法的组合。您的示例可以使用正则表达式解决,但是还有更多可能的情况......

&copy;[\s\d]*(?:<\/.+?>[^>]*>)?([^<]*)
Run Code Online (Sandbox Code Playgroud)

适用于您的三个样本。但仅适用于他们和类似的情况。

参见红宝石

解释:

&copy; // copyright symbol
[\s\d]* // followed by spaces or digits 
(?:</.+?>[^>]*>)? // maybe followed by a closing tag and another opening one
([^<]*) // than match anything up to the next tag
Run Code Online (Sandbox Code Playgroud)

有关如何在 javascript 和 jquery 中使用的信息,请参阅此答案。基本上你可以使用 match(/regex/) 函数:

var result = string.match(/&copy;[\s\d]*(?:<\/.+?>[^>]*>)?([^<]*)/)
Run Code Online (Sandbox Code Playgroud)