I am wondering if something like this is possible in python (3.2, if relevant).
with assign_match('(abc)(def)', 'abcdef') as (a, b):
print(a, b)
Where is the behavior:
- If the regular expression matches, the regular expression groups are obtained in
aandb- If there is a mismatch, it will throw an exception
- if a match
None, it just completely circumvents the context
My goal here is basically an extremely concise way of doing contextual behavior.
I tried to make the following context manager:
import re
class assign_match(object):
def __init__(self, regex, string):
self.regex = regex
self.string = string
def __enter__(self):
result = re.match(self.regex, self.string)
if result is None:
raise ValueError
else:
return result.groups()
def __exit__(self, type, value, traceback):
print(self, type, value, traceback)
with assign_match('(abc)(def)', 'abcdef') as (a, b):
print(a, b)
with assign_match('(abc)g', 'abcdef') as (a, b):
print(a, b)
It really works exactly the same as when the regular expressions match, but as you can see, it throws out ValueErrorif there is no match. Is there a way to get it to “jump” to the exit sequence?
Thank!!