def map(self, regex):
"""Decorate a function to map it to a regex expression.
Decorator that allows to map a Python function to a regex expression provided as argument. The regex expression
is parsed using the 're' module (https://docs.python.org/3/library/re.html). Therefore, all regex syntax that
this module supports is also supported by this regex matcher. To encapsulate arguments for the function in the
regex expression use named capture groups (see examples).
Inspired by the URL mapping of the Flask microframework (http://flask.pocoo.org/)
Args:
regex: An Python raw string (r'I am a raw string') that can be interpreted as regular expression
Returns:
func: The input function without modfication
Example:
The simplest case just maps a function to a name:
>>> mapper = FuncMapper()
>>> @mapper.map(r'a name')
... def my_func():
... return 'I, my_func, have been called'
>>> mapper('a name')
'I, my_func, have been called'
But you can also use variables by adding regex capture groups:
(Note: Only named match groups are supported!)
>>> mapper = FuncMapper()
>>> @mapper.map(r'(?P<first>\d+)\+(?P<second>\d+)')
... def adder(first, second):
... return '{} + {} = {}'.format(first, second, int(first) + int(second))
>>> mapper('3+5')
'3 + 5 = 8'
"""
def wrapper(f):
self._mapped_functions[regex] = f
compiled_regex = re.compile(regex)
if compiled_regex.groups > 0 and len(compiled_regex.groupindex) < compiled_regex.groups:
raise NotSupportedError("Only named matched groups are Supported!")
self._mapped_regex[regex] = compiled_regex
return f
return wrapper
评论列表
文章目录