Last active
January 21, 2016 03:50
-
-
Save polyvertex/e19ccde4c5dd3a0430c9 to your computer and use it in GitHub Desktop.
Small Python class to if/elif re.match()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ReMatch(): | |
""" | |
Small class to re.match() and to hold its result. | |
Convenient if you want to "if re.match(): ... elif re.match(): ..." | |
Usage: | |
rem = ReMatch() | |
if rem.match(...): | |
print(rem.group(1, "default value here")) | |
elif rem.match(...): | |
... | |
""" | |
def __init__(self): | |
self.m = None | |
#def __del__(self): | |
# re.purge() | |
def clear(self): | |
self.m = None | |
def match(self, *objects, **kwargs): | |
self.m = re.match(*objects, **kwargs) | |
return bool(self.m) | |
def group(self, index_or_name, default=None): | |
try: return self.m.group(index_or_name) | |
except IndexError: return default | |
def __bool__(self): | |
return bool(self.m) | |
def __getattr__(self, attr): | |
return getattr(self.m, attr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment