2014-07-12 22 views
0

我在其他帖子中看到,在做(?<!X|Y|Z)時這是解決非固定寬度模式問題的正確方法,但不適用於我。正則表達式後退問題

我嘗試以下

re.search(r'\b(?:(?<!Yummy)|(?<!Xoo))\bfoo\b', "Yummy foo", flags=re.UNICODE) is not None => True 
re.search(r'\b(?:(?<!Yummy)|(?<!Xoo))\bfoo\b', "Xoo foo", flags=re.UNICODE) is not None => True 
re.search(r'\b(?:(?<!Yummy)|(?<!Xoo))\bfoo\b', "other Yummy foo someone", flags=re.UNICODE) is not None => True 

它總是返回true,當它應該返回false。現在,如果我刪除或|,它工作正常。

re.search(r'\b(?:(?<!Yummy))\bfoo\b', "Yummy foo", flags=re.UNICODE) is not None => False 
re.search(r'\b(?<!Yummy)\bfoo\b', "Yummy foo", flags=re.UNICODE) is not None => False 
re.search(r'\b(?<!Yummy)\bfoo\b', " Yummy foo", flags=re.UNICODE) is not None => False 
re.search(r'\b(?<!Yummy)\bfoo\b', "other Yummy foo someone", flags=re.UNICODE) is not None => False 
re.search(r'\b(?<!Yummy)\bfoo\b', "foo someone", flags=re.UNICODE) is not None => True 
re.search(r'\b(?<!Yummy)\bfoo\b', "foo", flags=re.UNICODE) is not None => True 

有什麼建議嗎?

+0

,而不是更新的帖子,你爲什麼不問在一個單獨的問題。 **決定你想要問什麼?**因爲**根據你最後的編輯回答沒有任何答案的意義。** – Braj

+0

是的,對不起,因爲我試過你的建議,我意識到是更復雜或限制的問題。我去做! – Sebastian

回答

1

你不需要因爲lookbehinds都是零個寬度斷言使用的交替,你可以這樣寫:

re.search(r'\b(?<!\bYum)(?<!\bXooop)\s+foo\b', "Yum foo", flags=re.UNICODE) 
      ^^  ^
      | |   | 
      +-+---------+---These three assertions are tested at the same 
          position (i.e. immediatly before the \s+ match. 
          You can put them in any order you want, they are 
          only checks and don't eat characters. 
+0

我可以將'(?<!Yum)'和'(?<!Xoo)'結合到'(?<!(Yum | Xoo)'? – Braj

+0

允許PHP使用,但不能使用python。在這裏:https://pythex.org/ –

+0

我測試了它,它的工作原理 – Braj