Skip to main content
 首页 » 编程设计

python之如何从 Python 中的一组正则表达式匹配中提取第一个非空匹配

2025年05月04日24xxx_UU

假设我有一个正则表达式(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