2015-06-08 41 views
0

其他論壇成員, 我正在使用NotePad ++的最新版本,並且我需要關於RegEx的幫助,它將按照我指定的順序搜索多個標記的單詞。下面是我準備了一個例子:正則表達式按指定的順序查找多個標籤

<first> <second> <third> - 代表了我所需要的正則表達式來找到它們的順序三個標籤

<second> <first> <third> - 這些標籤不是我需要的順序,因此我想要的RegEx在搜索中忽略它們。

<third> <second> <first> <second> <second> - 這些標籤不是我需要的順序,也包含重複標籤我不需要在搜索中包含RegEx。

我已經嘗試過這個表達式:(first | second | third)

然而,似乎給我額外的數據,我不想。任何幫助將不勝感激。

+0

爲什麼不簡單'(第一第二第三)'?確保順序,確保所有三個存在... – knolleary

+0

這不是有效的XML。你的意思是''或'這裏匹配'? – Sobrique

回答

0

嘗試:

<first>[^<>]*<second>[^<>]*<third> 
+0

與我使用的相比,它似乎更有效。謝謝您的幫助。 – Matrix

0

你已經有點棘手的問題在這裏,因爲...很重要的是,XML是很難用正則表達式解析。有很多東西構成語義相同(或非常相似)的XML,這會破壞正則表達式。

所以真正的答案是'使用xpath',這是一個XML表達式,它......就像一個目錄路徑。作爲perl中的一個說明性示例(它將在Windows上工作)。

#!/usr/bin/perl 
use strict; 
use warnings; 

use XML::Twig; 

my $twig = XML::Twig->new('pretty_print' => 'indented')->parse(\*DATA); 

foreach my $match ($twig->root->get_xpath('//first/second/third')) { 
    print $match ->text, "\n"; 
} 

$twig->print; 

__DATA__ 
<root> 
<first> 
    <second> 
     <third>match here</third> 
    </second> 
</first> 
<second> 
    <first> 
     <third>not a match</third> 
    </first> 
</second> 
<first> <second> 
     <third>another match here</third></second> 
</first> 
<someparent> 
    <another> 
     <first><second><third>deeper nested match</third></second></first> 
    </another> 
</someparent> 
</root> 

//first/second/third一個「的XPath」會找到你想要的元素(//開頭表示「目前所有後代」)。我認爲Notepad ++支持XML插件。