简体   繁体   中英

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) . If I apply it to text 'foobar' I get a match object

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

How do I extract the 'b' from here? 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)
()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM