Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting captured group in one line

There is a known "pattern" to get the captured group value or an empty string if no match:

match = re.search('regex', 'text')
if match:
    value = match.group(1)
else:
    value = ""

or:

match = re.search('regex', 'text')
value = match.group(1) if match else ''

Is there a simple and pythonic way to do this in one line?

In other words, can I provide a default for a capturing group in case it's not found?


For example, I need to extract all alphanumeric characters (and _) from the text after the key= string:

>>> import re
>>> PATTERN = re.compile('key=(\w+)')
>>> def find_text(text):
...     match = PATTERN.search(text)
...     return match.group(1) if match else ''
... 
>>> find_text('foo=bar,key=value,beer=pub')
'value'
>>> find_text('no match here')
''

Is it possible for find_text() to be a one-liner?

It is just an example, I'm looking for a generic approach.

like image 456
alecxe Avatar asked Apr 29 '14 13:04

alecxe


1 Answers

You can play with the pattern, using an empty alternative at the end of the string in the capture group:

>>> re.search(r'((?<=key=)\w+|$)', 'foo=bar,key=value').group(1)
'value'
>>> re.search(r'((?<=key=)\w+|$)', 'no match here').group(1)
''
like image 60
Casimir et Hippolyte Avatar answered Oct 11 '22 11:10

Casimir et Hippolyte