Parser regex from named group
Here's a rough expression I'm working with /api/(?P<version>v[0-9]+)/endpoint
.
I would like to do two things:
- Get named groups, i.e.
version
- For named groups, get the associated expression, i.e.
v[0-9]+
The first part can be grabbed from the compiled regex:
>>> r = re.compile('/api/(?P<version>v[0-9]+)/endpoint')
>>> r.groupindex
{'version': 1}
I am wondering if there is anything that will allow me to grab an expression from a parsing group, for example.
+3
source to share
2 answers
You can create a base class that takes a template string, some parameters that are populated with kwargs (or a dictionary), then proxies all the other access attributes of the compiled regex like:
import re
class myre(object):
def __init__(self, template, *args, **kwargs):
self.expressions = dict(kwargs)
subs = {k: '(?P<{}>{})'.format(k, v) for k, v in self.expressions.items()}
self.rx = re.compile(template.format(**subs), *args)
def __getattr__(self, name):
return getattr(self.rx, name)
Then use the following:
r = myre('/api/{version}/endpoint', version='v[0-9]+')
print r.expressions['version'] # get expression for named group
# v[0-9]+
print list(r.expressions) # get list of named groups
# ['version']
# match as normal
print r.match('/api/v5/endpoint').group('version')
# v5
+2
source to share