[英]Python Regex match or potential match
如何使用Python的正則表達式模塊( re
)確定是否進行了匹配,或者可以進行潛在的匹配?
我想要一個正則表達式模式,以正確的順序搜索單詞模式,而不管它們之間是什么。 我想它返回一個功能Yes
,如果找到, Maybe
如果比賽仍然可以找到或No
,如果沒有匹配都可以找到。 我們正在尋找模式One|....|Two|....|Three
,下面是一些示例(注意名稱,數量或順序並不重要,我只關心三個單詞One
, Two
和Three
,介於兩者之間的可接受單詞是John
, Malkovich
, Stamos
和Travolta
)。
返回是:
One|John|Malkovich|Two|John|Stamos|Three|John|Travolta
返回是:
One|John|Two|John|Three|John
返回是:
One|Two|Three
返回可能:
One|Two
返回可能:
One
返回NO:
Three|Two|One
我了解這些示例並不是密不可分的,因此這是我讓正則表達式獲得肯定的結果:
if re.match('One\|(John\||Malkovich\||Stamos\||Travolta\|)*Two\|(John\||Malkovich\||Stamos\||Travolta\|)*Three\|(John\||Malkovich\||Stamos\||Travolta\|)*', 'One|John|Malkovich|Two|John|Stamos|Three|John|Travolta') != None
return 'Yes'
顯然,如果模式為Three|Two|One
則上述操作將失敗,並且我們可以返回No
,但是如何檢查Maybe
情況? 我考慮過像這樣嵌套括號(注意,未經測試)
if re.match('One\|((John\||Malkovich\||Stamos\||Travolta\|)*Two(\|(John\||Malkovich\||Stamos\||Travolta\|)*Three\|(John\||Malkovich\||Stamos\||Travolta\|)*)*)*', 'One|John|Malkovich|Two|John|Stamos|Three|John|Travolta') != None
return 'Yes'
但是我不認為這會做我想做的事。
我實際上並不是在尋找Travoltas
和Malkovichs
(我知道,這令人震驚)。 我正在與inotify模式匹配,例如IN_MOVE
, IN_CREATE
, IN_OPEN
,並且正在記錄它們並獲取數百個它們,然后進入,然后查找特定的模式,例如IN_ACCESS
... IN_OPEN
.... IN_MODIFY
,但是在某些情況下,我不希望在IN_DELETE
之后再輸入IN_OPEN
而在其他情況下,我希望這樣做。 我本質上是在進行模式匹配,以使用inotify來檢測文本編輯器何時變得瘋狂 ,他們試圖通過進行臨時文件交換保存而不是僅僅修改文件來壓垮程序員的靈魂。 我不想立即釋放這些日志,但是我只想保留它們必要的時間。 Maybe
意味着不要擦除日志。 Yes
意思是先執行某些操作然后清除日志, No
意思是不執行任何操作,但仍然清除日志。 因為我對每個程序都有多個規則(例如vim
v gedit
v emacs
),所以我想使用正則表達式,該表達式更易於閱讀,更易於編寫,然后創建大型樹,或者按照用戶Joel的建議進行操作帶有循環的單詞
我不會為此使用正則表達式。 但這絕對是可能的:
regex = re.compile(
r"""^ # Start of string
(?: # Match...
(?: # one of the following:
One() # One (use empty capturing group to indicate match)
| # or
\1Two() # Two if One has matched previously
| # or
\1\2Three() # Three if One and Two have matched previously
| # or
John # any of the other strings
| # etc.
Malkovich
|
Stamos
|
Travolta
) # End of alternation
\|? # followed by optional separator
)* # any number of repeats
$ # until the end of the string.""",
re.VERBOSE)
現在,您可以通過檢查是否完全匹配來檢查是和否:
>>> yes = regex.match("One|John|Malkovich|Two|John|Stamos|Three|John|Travolta")
>>> yes
<_sre.SRE_Match object at 0x0000000001F90620>
>>> maybe = regex.match("One|John|Malkovich|Two|John|Stamos")
>>> maybe
<_sre.SRE_Match object at 0x0000000001F904F0>
您可以通過檢查所有組是否都參加了比賽(即不是None
)來區分YES和MAYBE:
>>> yes.groups()
('', '', '')
>>> maybe.groups()
('', '', None)
如果正則表達式根本不匹配,那么對您來說是不對的:
>>> no = regex.match("Three|Two|One")
>>> no is None
True
有些人在遇到問題時會認為“我知道,我會使用正則表達式”。 現在他們有兩個問題。 -傑米·扎溫斯基
也許像這樣的算法會更合適。 這是一些偽代碼。
matchlist.current = matchlist.first()
for each word in input
if word = matchlist.current
matchlist.current = matchlist.next() // assuming next returns null if at end of list
else if not allowedlist.contains(word)
return 'No'
if matchlist.current = null // we hit the end of the list
return 'Yes'
return 'Maybe'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.