【问题标题】:select HTML text element with regex?使用正则表达式选择 HTML 文本元素?
【发布时间】:2011-12-18 07:35:10
【问题描述】:

我想在HTML文档中查找©,基本上得到版权归属的实体。

版权行有几种不同的显示方式:

<p class="bg-copy">&copy; 2011  The New York Times Company</p>

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

<br>Published since 1996<br>Copyright &copy; CounterPunch<br>
All rights reserved.<br>

我想忽略日期和中间标签,只获取“The New York Times Company”或“Counterpunch”。

我在 JavaScript 或 JQuery 中使用 regex 的方法并不多,尽管我觉得它可能会导致头疼的问题。如果有更好的方法,请告诉我。

【问题讨论】:

  • 不要使用正则表达式,而是使用 DOM 树来查找您要查找的内容。一些链接:howtocreate.co.uk/tutorials/javascript/dombasics
  • 通常你会得到的响应是——请不要使用正则表达式进行 JS 解析。使用 JS 解析器。问题是 - 你可以吗?
  • @ZenMaster Regex 不是这种解析的工具。

标签: javascript jquery regex html-parsing text-extraction


【解决方案1】:

对于一个健壮的解决方案,您可能需要结合使用 DOM 导航和一些启发式方法。你的例子可以用正则表达式解决,但还有更多可能的场景......

&copy;[\s\d]*(?:<\/.+?>[^>]*>)?([^<]*)

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

rubular

解释:

&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

请参阅this 答案,了解如何在带有 jquery 的 javascript 中使用。基本上你可以使用 match(/regex/) 函数:

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

【讨论】:

  • 谢谢,我知道这行得通,但我决定找到“©”在页面中编码并解析该元素。但是,现在我遇到了麻烦:stackoverflow.com/questions/8282250/…
  • 另外,您介意为我分解您的正则表达式吗?我真的不明白。我将如何在 javascript 中使用它?
【解决方案2】:
$('*:contains(©)').filter(function(){
    return $(this).find('*:contains(©)').length == 0
}).text();

在这里测试http://jsfiddle.net/unloco/kGPYA/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 2019-05-18
    • 1970-01-01
    • 2012-06-23
    • 2013-10-08
    • 1970-01-01
    • 2011-11-03
    相关资源
    最近更新 更多