2017-07-08 114 views
-2

我有XML的文件,這種結構如何從正則表達式搜索中排除某些詞?

<item><rank>15</rank>...<price>100</price></item> 
<item><rank>15</rank>...<price>200</price></item> 
<item><rank>15</rank>...<price>500</price></item> 

從上面XML...手段:一些不同的標記,這在某種程度上說明的項目(可以是任何標籤)

所以我需要找項目與price=500並替換rank它。

<item><rank>\d+<\/rank>(.*)<price>500<\/price><\/item> 

但這正則表達式會發現是內容在年底從第一<item><price>500</price></item>啓動這三個標籤。

所以我需要排除</item>(.*)在搜索。

+4

使用xml解析器。 –

+0

使用捕獲組?請參閱[this](https://regex101.com/r/Ohr3Wa/1) –

+1

您使用哪些編程語言? –

回答

0

this regex

/(?:<item>(?:<rank>(\d+)<\/rank>)(?:(?!<\/item>).)*(?:<price>500<\/price>)<\/item>)/igm 

通過使用圓括號,您可以創建捕獲組; ?:是一個非捕獲組(意味着你對它的內容不感興趣)。
igm表示不區分大小寫,全局和多行。
(?!sth)是負向前視,意味着我們將放棄sth。通過步驟

步驟:(來自外代碼)

(?:<item> ... <\/item>) # we're interested in things beginning with <item> and ending with </item> and we're not capturing the group 

... (?:<rank>(\d+)<\/rank>) ... # there's a rank tag, we're not capturing it, but we're capturing the digits within the tag 

... (?:(?!<\/item>).)* ... # the crux of the problem, we're looking at any character except <\/item> 

... (?:<price>500<\/price>)<\/item>) # the "line" ends with these tags 

希望它幫助。

相關問題