2013-10-02 16 views
0

我的正則表達式有什麼問題?有多個結果的正則表達式

"/Blabla\(2\)&nbsp;:.*<tr><td class=\"generic\">(.*)<\/td>.+<\/tr>/Uis" 

....

<tr> 
<td class="aaa">Blabla(1)&nbsp;:</td> 
<td> 
<table class="bbb"><tbody> 
<tr class="ccc"><th>title1</th><th>title2</th><th>title3</th></tr> 
<tr><td class="generic">word1</td><td class="generic">word2 </td><td class="generic">word3</td></tr> 
<tr><td class="generic">word4</td><td class="generic">word5 </td><td class="generic">word6</td></tr> 
</tbody></table> 
</td> 
</tr> 

<tr> 
<td class="aaa">Blabla(2)&nbsp;:</td> 
<td> 
<table class="bbb"><tbody> 
<tr class="ccc"><th>title1</th><th>title2</th><th>title3</th></tr> 
<tr><td class="generic">word1b</td><td class="generic">word2b </td><td class="generic">word3b</td></tr> 
<tr><td class="generic">word4b</td><td class="generic">word5b </td><td class="generic">word6b</td></tr> 
</tbody></table> 
</td> 
</tr 

我想要做的是讓每個TR的第一個TD從塊與BLABLA開頭的內容(2)。

因此,預期的答案是word1b和word4b 但只有返回第一...

謝謝您的幫助。請不要回答我使用DOM導航器,這在我的情況下是不可能的。

+3

您正在使用哪種語言?最重要的是你如何使用它? –

+1

**不要使用正則表達式來解析HTML。使用合適的HTML解析模塊**您無法可靠地使用正則表達式解析HTML,並且您將面臨悲傷和挫折。只要HTML從你的期望改變,你的代碼就會被破壞。請參閱http://htmlparsing.com/php或[this SO thread](http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php)如何使用已經編寫,測試和調試的PHP模塊正確解析HTML的示例。 –

+0

@Barmar'U'國旗將'*'變成非理智和'*?'變成貪婪 – Jerry

回答

1

這是一個有趣的正則表達式,我在其中學到了不懂的標誌,很好!

而對於你的問題,你可能會利用\G以前的比賽和標誌g後立即匹配,假設PCRE引擎:

/(?:Blabla\(2\)&nbsp;:|(?<!^)\G).*<tr><td class=\"generic\">(.*)<\/td>.+<\/tr>/Uisg 

regex101 demo

或更短一點不同的分隔符:

'~(?:Blabla\(2\)&nbsp;:|(?<!^)\G).*<tr><td class="generic">(.*)</td>.+</tr>~Uisg' 
+0

太棒了!正是我在找什麼!謝謝:) – wewereweb

+0

@wewereweb不客氣:) – Jerry

0

感謝@Jerry,今天我學到了新的技巧:

(Blabla\(2\)&nbsp;:.*?|\G)<tr><td class=\"generic\">\K([^<]+).+?<\/tr>\r\n