Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Regex: Check for match and capture groups

I want to ensure that a string matches a regular expression using an if statement, and store capture groups simultaneously. I think the following code shows what I want, but it is syntactically invalid. Is there a way to achieve the following elegantly?

yyyyq_format = "19984"

if regex_match = re.search("^(\d{4})(\d)$", yyyyq_format):
    found_q = regex_match[2]
else:
    raise ValueError("Format \"yyyyq\" is not followed.")

I know the following works (is this my only option?):

yyyyq_format = "19984"
regex_match = re.search("^(\d{4})(\d)$", yyyyq_format)

if regex_match:
    found_q = regex_match[2]
else:
    raise ValueError("Format \"yyyyq\" is not followed.")
like image 723
Hurricane Development Avatar asked Dec 30 '25 14:12

Hurricane Development


2 Answers

PEP-572 (assignment expressions) implemeted what is being called the walrus operator that you can use to evaluate an expression and assign the return to a name in one go e.g.:

if regex_match := re.search("^(\d{4})(\d)$", yyyyq_format):
    found_q = regex_match[2]
else:
    raise ValueError("Format \"yyyyq\" is not followed.")

Note the : before =.

This is (will be) available in Python 3.8.

Before that, your second option is the only way I believe.

like image 70
heemayl Avatar answered Jan 01 '26 02:01

heemayl


Walrus operator := in Python 3.8 is one option, or you can do for else statement (note the re.finditer):

import re

yyyyq_format = "19984"

for g in re.finditer("^(\d{4})(\d)$", yyyyq_format):
    found_q = g[2]
    break
else:
    raise ValueError("Format \"yyyyq\" is not followed.")

print(found_q)

Prints:

4
like image 25
Andrej Kesely Avatar answered Jan 01 '26 04:01

Andrej Kesely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!