2013-06-03 64 views
0

好的,正則表達式應該使用XML來代替元素,與孩子匹配元素

有一些代碼混亂。應該使用XML/DOM,相反,暫時需要使用正則表達式來快速修復字符串。

我有一個元素,具有相同類型的子節點。

例如。

AAA <z id="z11"> BBB <z id="z22"> CCC </z> DDD </z> endOfString. 

有沒有在正則表達式中匹配此字符串中父節點的方法。

<z id="z11"> BBB <z id="z22"> CCC </z> DDD </z> 

是的,我知道這一切都需要重新編寫,但認爲這是一個純粹的正則表達式問題。

謝謝。

+0

的規範答案一定不要錯過:http://stackoverflow.com/問題/ 1732348 /正則表達式匹配開放標籤,除了-XHTML-自足標籤/ 1732454#1732454 – 2013-06-03 09:58:03

回答

0

好吧,這肯定不是最好的方法,但你說你想正則表達式,所以這裏是這個正則表達式:

(<z id="[a-zA-Z0-9]+">.*?<z id="[a-zA-Z0-9]+">.*?</z>.*?</z>) 

+--------------+ 
| Explanation: | 
+--------------+ 

(   # indicates the start of a capturing group 
<z id="  # the first part of the parent-tag 
[a-zA-Z0-9]+ # matches any combination of letters and numbers for the id 
">   # end of the opening parent-tag 
.*?   # matches everything (ungreedy) up to the start of the child tag 
<z id="  # the first part of the child-tag 
[a-zA-Z0-9]+ # matches any combination of letters and numbers for the id 
">   # end of the opening child-tag 
.*?   # matches everything (ungreedy) up to the closing tag 
</z>   # matches the closing tag (of the child) 
.*?   # matches everything (ungreedy) up to the closing tag 
</z>   # matches the closing tag (of the parent) 
相關問題