[英]Shortest match in Regex
这是我的正则表达式:
/<strong>.*ingredients.*<\/ul>/im
假设源代码:
<strong>Contest closes on Thursday May 10th 2012 at 9pm PST</strong></div>
<br />
<br />
<br />
* I am not affiliated with Blue Marble Brands or Ines Rosales Tortas in any way. I am not sponsored by them and did not receive any compensation to write this post...I just simply think the Tortas are wonderful!<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-35J5vNrXkqE/T6htXTafrmI/AAAAAAAAA5E/g2mtiuSpSmw/s1600/food+003.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="480" mea="true" src="http://1.bp.blogspot.com/-35J5vNrXkqE/T6htXTafrmI/AAAAAAAAA5E/g2mtiuSpSmw/s640/food+003.JPG" width="640" /></a></div>
<br />
<strong><span style="font-size: large;">Ingredients:</span></strong><br />
<ul>
<li>Ines Rosales Rosemary and Thyme Tortas</li>
<li>Pizza Sauce (ready made in a jar)</li>
<li>Roma Tomatoes</li>
<li>Roasted Red Peppers </li>
<li>Marinated Artichoke Hearts</li>
<li>Olives (I used Pitted Spanish Manzanilla Olives)</li>
<li>Daiya Vegan Mozzarella Cheese</li>
</ul>
<span style="font-size: large;"><strong>Directions:</strong></span><br />
<br />
Spread small amount of pizza sauce over Torta.
正则表达式很贪婪,可以从<strong>Contest...</ul>
但最短的匹配应产生<strong><span style="font-size: large;">Ingredients...</ul>
这是我的要旨: https : //gist.github.com/3660370
:: edit ::请在强标签和成分之间以及成分和ul之间留出灵活性。
尝试这个:
/<strong><span.*ingredients.*<\/ul>/im
请不要对html进行正则表达式。 请改用Nokogiri或类似的库。
这应该工作:
/(?!<strong>.*<strong>.*<\/ul>)<strong>.*?ingredients.*?<\/ul>/im
在这里测试
基本上,正则表达式使用负前瞻避免在<\\ul\u0026gt;
<strong>
之前使用多个<strong>
,例如: (?!<strong>.*<strong>.*<\\/ul>)
我认为这是您要寻找的:
/<strong>(?:(?!<strong>).)*ingredients.*?<\/ul>/im
用(?:(?!<strong>).)*
替换第一个.*
可以在找到ingredients
之前匹配除另一个<strong>
标记之外的任何其他内容。 在那之后,非贪婪的.*?
导致它在看到的</ul>
的第一个实例处停止匹配。 (您的样本仅包含一个<UL>
元素,但我假设实际数据可能包含更多元素。)
通常会出现警告:即使在完全有效的HTML中,也可以通过多种方法来欺骗该正则表达式,更不用说我们通常会看到的麻烦了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.