假设我有一个正则表达式(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
关于python - 如何从 Python 中的一组正则表达式匹配中提取第一个非空匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2498935/