简体   繁体   中英

Capture a regex in a if condition

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]

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.

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

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