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.")
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With