使用正则表达式在html中查找一个描述性文本块

时间:2014-05-22 03:46:48

标签: regex

我正在试图弄清楚如何使用预测来尝试在html页面中捕获描述性文本,例如

<div class="itemBanner" style="float:left; padding:10px">
<div style="padding-right:5px; padding-bottom:5px">
<div class="itemBanner">
HTML Tags Stripper is designed to strip HTML tags from the text. It will also strip embedded JavaScript code, style information (style sheets), as well as code inside php/asp tags (&lt;?php ?&gt; &lt;%php ?&gt; &lt;% %&gt;). It will also replace sequence of new line characters (multiple) with only one. <b>Allow tags</b> feature is session sticky, i.e. it will remember allowed tags list, so you will have to type them only once.<p></p>You can either provide text in text area below, or enter URL of the web page. If URL provided then HTML Tags Stripper will visit web-page for its contents.<p></p>
<b>Known issues:</b><br />

我想出了一个寻找'&gt;'的正则表达式在'&lt;'之前至少有150个字符会做的。

我到目前为止最接近的是:

  

(([^&LT;]){1500})&LT;

在字符串之前和之后的句子和其他字符之类的内容仍然遗漏。

1 个答案:

答案 0 :(得分:1)

你的正则表达式将匹配任何既不“。”的东西。也不是“&lt;” 1到500次,然后是“&lt;”。

假设您要捕获从itemBanner div到下一个结束div的所有内容,您可以使用以下元素:

  • <div class="itemBanner"> - 显式匹配
  • () - 用于引用的parathentical wrap,例如match[1]
  • .*? - 任意长度的字符,非贪婪(尽可能少)
  • <\/div> - 显式匹配,转义为'/'

形成这个Ruby正则表达式:

item_banner_div_regex = /<div class="itemBanner">(.*?)<\/div>/
match = item_banner_div_regex.match(html)
inside_item_banner_div = match && match[1]

注意:确切的正则表达式取决于您正在使用的实现。