2016-09-30 55 views
2

下面的模式花了我很長時間才發現。當我終於找到它時,事實證明它在Python中不起作用。有誰知道是否有替代方案?PCRE正則表達式(* COMMIT)等效於Python

(*COMMIT)定義:如果模式的其餘部分不匹配,則會導致整個匹配失敗。

(*FAIL)在Python中也不起作用。但是這可以由(?!)取代。取自

+-----------------------------------------------+ 
|Pattern:          | 
|^.*park(*COMMIT)(*FAIL)|dog     | 
+-------------------------------------+---------+ 
|Subject        | Matches | 
+-----------------------------------------------+ 
|The dog and the man play in the park.| FALSE | 
|Man I love that dog!     | TRUE | 
|I'm dog tired      | TRUE | 
|The dog park is no place for man. | FALSE | 
|park next to this dog's man.   | FALSE | 
+-------------------------------------+---------+ 

例子: regex match substring unless another substring matches

+0

您可以執行r(^!。 8qDQDG/1) – dawg

+0

該正則表達式在PCRE中也不起作用;你修改它的答案是錯誤的。但是,沒關係控制動詞,lookaheads在兩種口味中都能正常工作,正如[Sebastian的回答](http://stackoverflow.com/a/39796696/20938)所示。 –

回答

2

這可能不是一個通用的替代品,但對於你的情況,你可以用向前看符號工作,斷言狗是匹配的,但公園是不是:^(?=.*dog)(?!.*park).*$

您在regex101上的樣本

+0

這工作,albiet迭代大量數據時非常緩慢,但它的工作原理。我認爲這個倍數是減慢速度的。 – Gernatch

+0

更新:嗯,我不認爲你的例子很慢。我正在嘗試添加倍數,^(?=。* dog |。* cat |。* bird)(?!。* .park |。* pool |。* trail)* $這就是放慢速度的原因。我確定。 – Gernatch

+0

無視。我在循環中發生錯誤。這個解決方案對我來說很完美。 – Gernatch