Python 中开发pattern的string模板(template) 实例详解
定制pattern的string模板(template)详解
string.Template的pattern是一个正则表达式,可以通过覆盖pattern属性,定义新的正则表达式.
如:使用新的定界符"{{",把{{var}}作为变量语法.
代码:
#-*-coding:utf-8-*- ''''' Createdon2014.6.5 @author:Administrator @edition:python3.3.0,eclipsepydev ''' importstring t=string.Template('$var') print(t.pattern.pattern) classMyTemplate(string.Template): delimiter='{{' pattern=r''''' \{\{(?: (?P\{\{)|#Escapesequenceoftwodelimiters (?P [_a-z][_a-z0-9]*)\}\}|#delimiterandaPythonidentifier {(?P [_a-z][_a-z0-9]*)}\}\}|#delimiterandabracedidentifier (?P )#Otherill-formeddelimiterexprs ) ''' t2=MyTemplate(''''' {{{{ {{var}} ''') print('MATCHES:',t2.pattern.findall(t2.template)) print('SUBSTITUTED:',t2.safe_substitute(var='replacement'))
输出:
\$(?: (?P\$)|#Escapesequenceoftwodelimiters (?P [_a-z][_a-z0-9]*)|#delimiterandaPythonidentifier {(?P [_a-z][_a-z0-9]*)}|#delimiterandabracedidentifier (?P )#Otherill-formeddelimiterexprs ) MATCHES:[('{{','','',''),('','var','','')] SUBSTITUTED: {{ replacement
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!