My dilemma: I'm passing my function a string that I need to then perform numerous regex manipulations on. The logic is if there's a match in the first regex, do one thing. If no match, check for a match with the second and do something else, if not check the third, and so forth. I could do something like this:
if re.match('regex1', string):
match = re.match('regex1', string)
# Manipulate match.group(n) and return
elif re.match('regex2', string):
match = re.match('regex2', string)
# Do second manipulation
[etc.]
However, this feels unnecessarily verbose, and usually when that's the case it means there's a better way that I'm either overlooking or don't yet know about.
Does anyone have a suggestion for a better way to do this (better from a code-appearance standpoint, a memory usage standpoint, or both)?
I had the same problem as yours. Here´s my solution:
It´s a slightly modified solution from the answer of Extracting info from large structured text files
Hmm... you could use something with the
with
construct... umAre the manipulations for each regex similar? If so, try this:
Here your regexs and matches are not repeated twice:
You can use this class like so:
Generally speaking, in these sorts of situations, you want to make the code "data driven". That is, put the important information in a container, and loop through it.
In your case, the important information is (string, function) pairs.