简体   繁体   English

如何从Python中的一组regexp匹配中提取第一个非null匹配?

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

Suppose I have a regular expression (a)|(b)|(c)|(d) . 假设我有一个正则表达式(a)|(b)|(c)|(d) If I apply it to text 'foobar' I get a match object 如果我将其应用于文本'foobar'则会得到一个匹配对象

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

How do I extract the 'b' from here? 如何从此处提取'b' Or in general, how do I extract the first match from an unknown number of groups (can happen when the regexp was built dynamically)? 还是一般来说,如何从未知数量的组中提取第一个匹配项(当动态创建正则表达式时会发生这种情况)?

>>> 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