I am wanting to check if one of a number of regex matches succeeds. If it does, I want access to the groups in the match. If I didn't need the groups, I could do something like this:
if re.match(pobj1,string):
# First match worked
elif re.match(pobj2,string):
# First match failed, but second one worked.
[...]
Since I haven't assigned the result of the match to anything, I don't see how to access any of the groups that were part of the match. So instead I'm assigning the matches to a variable before the conditional. But that means I'm running all the matches every time, not just the necessary ones.
mobj1 = re.match(pobj1,string)
mobj2 = re.match(pobj2,string) # Might be expensive
if mobj1:
# First match succeeded. Use the match information
print(mobj1.group(1))
elif mobj2:
# First match failed, but second one worked. Use info from #2.
print(mobj2.group(1))
[...]
How do I only run the matches that are necessary, while still being able to access the groups from that match at a later time?
Aucun commentaire:
Enregistrer un commentaire