Created
December 28, 2013 05:03
-
-
Save sochoa/8156261 to your computer and use it in GitHub Desktop.
Returning a basic type for each attempt at a regex match. Also memoizing the calls to the re module for speed.
This file contains 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
import re | |
def memoize(f): | |
class memodict(dict): | |
def __init__(self, f): | |
self.f = f | |
def __call__(self, *args): | |
return self[args] | |
def __missing__(self, key): | |
ret = self[key] = self.f(*key) | |
return ret | |
return memodict(f) | |
@memoize | |
def _re(method, pattern, value, *args): | |
return getattr(re, method)(pattern, value, *args) | |
def first_match(pattern, value, *args): | |
try: | |
groups = _re('search', pattern, value, *args).groups()[0] | |
except: | |
return None | |
def all_matches(pattern, value, *args): | |
try: | |
return _re('findall', pattern, value, *args) | |
except: | |
return [] | |
def dict_match(pattern, value, *args): | |
try: | |
return _re('search', pattern, value, *args).groupdict() | |
except: | |
return {} | |
def any_match(pattern, value, *args): | |
return (all_matches(pattern, value, *args), | |
dict_match(pattern, value, *args)) | |
print any_match('(?P<myGroup>foo|bar|baz)', 'foo bar baz', re.I) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment