2014-09-26 40 views
4

鑑於以下文字,您將使用什麼PCRE正則表達式來提取以粗體標記的零件?多行,多變貪婪,正則表達式

 
00:20314 lorem ipsum 
    want this 
    kryptonite 

00:02314 quux 
    padding 
    dont want this 

00:03124 foo 
    neither this 

00:01324 foo 
    but we want this 
    stalagmite 

00:02134 tralala 
    not this 

00:03124 bar foo 
    and we want this 
    kryptonite but not this(!) 

00:02134 foo bar 
    and not this either 

00:dolor sit amet 
    EOF 

督察,我們想抽取開始,在正則表達式方面的部分,用「^ 0」和結束「(氪石|石筍)」。

一直在嘲笑這一點,發現它是一個難題。 TIA!

+0

有幾種方法可以做到這一點。分隔符可以放在身體中嗎? – sln 2014-09-26 20:08:02

+0

分隔這個唯一的東西不需要其他的'^ 0'在身體。 – sln 2014-09-26 20:28:45

回答

-1

^(00:?*(氪石|石筍)),與爲此s修正

+0

只是與預期的輸出不匹配 – HamZa 2014-09-26 20:45:55

3

這看起來像它的工作原理。

# (?ms)^0(?:(?!(?:^0|kryptonite|stalagmite)).)*(kryptonite|stalagmite) 

(?ms) 
^ 0 
(?: 
     (?! 
      (?:^0 | kryptonite | stalagmite) 
    ) 
     . 
)* 
(kryptonite | stalagmite) 
+0

相同的概念,但也包含關鍵字。尼斯=) – hwnd 2014-09-26 20:25:38

+0

關鍵字可能不需要。你的是更好的。 – sln 2014-09-26 20:27:23

+0

還是,想一想=)(+1) – hwnd 2014-09-26 20:28:02

2

我相信這將是最有效的:

^0(?:\R(?!\R)|.)*?\b(?:kryptonite|stalagmite)\b 

Demo


很顯然,我們開始^0,然後用兩種kryptonitestalagmite結束(在非拍攝組,爲它的包圍)由\b word boundaries包圍。

(?:\R(?!\R)|.)*?雖然是有趣的部分,所以讓我們來分解它。首先一個關鍵概念是PCRE的\R newline sequence

(?:  (?# start non-capturing group for repetition) 
    \R  (?# match a newline character) 
    (?!\R) (?# not followed by another newline) 
|  (?# OR) 
    .  (?# match any character, except newline) 
)*?  (?# lazily repeat this group) 
+0

你需要在表達式中添加'$' – HamZa 2014-09-26 20:42:34

+1

@HamZa,我不這麼認爲:'00:03124 bar foo,我們想要這個kryptonite,但不是這個(!)' – Sam 2014-09-26 20:43:34

+0

好的,我誤解了需求。我的錯... – HamZa 2014-09-26 20:44:46