Skip to content

Instantly share code, notes, and snippets.

@cwvh
Created December 9, 2011 03:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cwvh/1449952 to your computer and use it in GitHub Desktop.
Save cwvh/1449952 to your computer and use it in GitHub Desktop.
Clean code with better named captures.
"""`namedmatch` mimics `re.match` but also creates attributes based on the
values of the named captures.
Example
>>> string = 'foo bar baz'
>>> match = namedmatch(r'(?P<start>\w+) (?P<end>\w+)', string)
>>> print match.start
"foo"
>>> print match.end
"bar"
>>> print match
namedmatch({'start': 'foo', 'end': 'bar'})
"""
from collections import namedtuple
import re
def namedmatch(pattern, string, flags=0, matcher=re.match):
match = matcher(pattern, string, flags)
if match is None:
return None
groupdict = match.groupdict()
NamedMatch = namedtuple('namedmatch', groupdict.iterkeys())
return NamedMatch(*groupdict.itervalues())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment