簡體   English   中英

如何從Python中的一組regexp匹配中提取第一個非null匹配?

[英]How to extract the first non-Null match from a group of regexp matches in Python?

假設我有一個正則表達式(a)|(b)|(c)|(d) 如果我將其應用於文本'foobar'則會得到一個匹配對象

>>> compiled = re.compile('(a)|(b)|(c)|(d)')
>>> compiled.search('foobar').groups()
(None, 'b', None, None)

如何從此處提取'b' 還是一般來說,如何從未知數量的組中提取第一個匹配項(當動態創建正則表達式時會發生這種情況)?

>>> g = (None, 'b', None, None)
>>> next(x for x in g if x is not None)
'b'

>>> g = (None, None, None)
>>> next((x for x in g if x is not None), "default")  # try this with filter :)
'default'

>>> g = (None, None, None)  # so you know what happens, and what you could catch
>>> next(x for x in g if x is not None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
reduce(lambda x, y : (x, y)[x is None], groups, None)
filter(lambda x : x is not None, groups)[0]
>>> g = (None,'b',None,None)
>>> filter(None,g)
('b',)
>>> h = (None,None,None)
>>> filter(None,h)
()

暫無
暫無

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

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