Detailed description of the string template (template) for pattern Development in Python, pythonpattern
Detailed description of the string template for customizing pattern
The pattern of string. Template is a regular expression. You can overwrite the pattern attribute to define a new regular expression.
For example, use the new separator "{" and use {var} as the variable syntax.
Code:
# -*- coding: utf-8 -*- ''''' Created on 2014.6.5 @author: Administrator @edition : python 3.3.0, eclipse pydev ''' import string t = string.Template('$var') print(t.pattern.pattern) class MyTemplate(string.Template): delimiter = '{{' pattern = r''''' \{\{(?: (?P<escaped>\{\{) | # Escape sequence of two delimiters (?P<named>[_a-z][_a-z0-9]*)\}\} | # delimiter and a Python identifier {(?P<braced>[_a-z][_a-z0-9]*)}\}\} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) ''' t2 = MyTemplate(''''' {{{{ {{var}} ''') print('MATCHES: ', t2.pattern.findall(t2.template)) print('SUBSTITUTED: ', t2.safe_substitute(var='replacement'))
Output:
\$(?: (?P<escaped>\$) | # Escape sequence of two delimiters (?P<named>[_a-z][_a-z0-9]*) | # delimiter and a Python identifier {(?P<braced>[_a-z][_a-z0-9]*)} | # delimiter and a braced identifier (?P<invalid>) # Other ill-formed delimiter exprs ) MATCHES: [('{{', '', '', ''), ('', 'var', '', '')] SUBSTITUTED: {{ replacement
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!