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.
re.findall()
? – Bazarjoin
. If it's empty you'd get an empty string back. – Bazar''.join(re.findall(r'key=(\w+)', text))
? – Bazarsearch
, but anyway it's an option too. Thank you. – Pitchblack