1

I would like to capture the match of my regex directly in my if condition. I know it was possible in PHP, but I don't know how to do it in a Pythonic way. So I run it twice and it's not sexy at all...

str = 'Test string 178-126-587-0 with a match'
if re.findall(r'[0-9]{3}-[0-9]{3}-[0-9]{3}-[0-9]', str) != []:
    match = re.findall(r'[0-9]{3}-[0-9]{3}-[0-9]{3}-[0-9]', str)[0]
Maxime
  • 594
  • 5
  • 17

2 Answers2

3

You can't do in-line variable assignment while using a conditional construct in Python, you need to leverage a temp variable. In your case, re.search would do as you are taking the first element anyway and there is no captured group:

match_ = re.search(r'[0-9]{3}-[0-9]{3}-[0-9]{3}-[0-9]', str_)
if match_:
    match = match_.group()

Regarding your original example, empty list is falsey in Python, so:

if not some_list:
    # Do stuffs

would do.

heemayl
  • 39,294
  • 7
  • 70
  • 76
  • Thanks heemayl, but I don't get the ".group()" thing. Why not match[0] since there is only one match using search()? – Maxime Jan 31 '18 at 20:48
  • @Maxime Unlike `re.findall`, `re.search` returns a match object, not a list. See https://docs.python.org/3/library/re.html#match-objects – heemayl Jan 31 '18 at 20:50
0

I found this solution with the := operator reading this post:

str = 'Test string 178-126-587-0 with a match'
if (match := re.search(r'[0-9]{3}-[0-9]{3}-[0-9]{3}-[0-9]', str)):
    match = match.group()
Maxime
  • 594
  • 5
  • 17