簡體   English   中英

(Python)正則表達式:匹配不在(靜態)字符串列表中的所有內容

[英](Python) regex: Match everything which is NOT in a (static) list of string

假設我有(靜態)列表['DOG', 'CAT', 'LEOPARD'] (可能不同長度的字符串)。

我知道如何構造正則表達式,以捕獲屬於此列表的成對逗號分隔的動物:

from re import search
search('^(DOG|CAT|LEOPARD),(DOG|CAT|LEOPARD)$', 'DOG,LEOPARD') #-> Match
search('^(DOG|CAT|LEOPARD),(DOG|CAT|LEOPARD)$', 'LEOPARD,WHALE') #-> No match

我現在想要一個匹配成對動物的正則表達式,其中沒有一個屬於我的動物列表。 使用虛擬運算符! ,我想要的是:

from re import search
search('^!(DOG|CAT|LEOPARD),!(DOG|CAT|LEOPARD)$', 'DOG,LEOPARD') #-> No match
search('^!(DOG|CAT|LEOPARD),!(DOG|CAT|LEOPARD)$', 'CHIMP,WHALE') #-> Match

是否存在這樣的運算符?

如果不是,是否有一種簡單的方法可以通過鏈接現有的操作符來構造這樣的運算符(我正在編寫正則表達式構造函數,因此,可讀性和regex的長度都不是重要因素)?

注意 :我知道我向正則表達式引擎提出了很多要求。

注2 :我對不依賴於正則表達式的解決方案不感興趣,因為此問題與我已經使用(非常復雜的)正則表達式解決的一個更大的問題集成在一起。

除了使用正則表達式,您還可以使用集合並測試交集:

>>> a = set(['DOG', 'CAT', 'LEOPARD'])
>>> b = set('DOG,LEOPARD'.split(','))
>>> True if a.intersection(b) else False

為什么不使用字符串和內置函數代替正則表達式?

def matcher(no, s):
    return not any(word in no for word in set(s.split(',')))

結果:

>>> matcher({'DOG', 'CAT', 'LEOPARD'}, 'DOG,LEOPARD')
False
>>> matcher({'DOG', 'CAT', 'LEOPARD'}, 'CHIMP,WHALE')
True

您正在尋找環顧四周

^(?!(?:DOG|CAT|LEOPARD),)[^,]+,(?!(?:DOG|CAT|LEOPARD)$)[^,]+$

模式細分:

^     assert position at start of string
(?!   assert the following text does NOT match...
    (?:DOG|CAT|LEOPARD) ...one of these 3 words...
    ,   ...followed by a comma. The comma is essential, because it makes sure that the text
           IS dog or cat or leopard. Without the comma, the regex would check if the text
           STARTS WITH dog, cat or leopard.
)
[^,]+   if we've reached this point, we know the animal isn't cat, dog or leopard. Match up
        until the next comma.
,       consume the comma
(?!     same as before, except this time...
    (?:DOG|CAT|LEOPARD)
    $   ...assert end of string instead of comma
)
[^,]+
$

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM