簡體   English   中英

正則表達式中最短的比賽

[英]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.&nbsp; I am not sponsored by them and did not receive any compensation to write this post...I just simply think the&nbsp;Tortas&nbsp;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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM