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.")
Aucun commentaire:
Enregistrer un commentaire