首页 > 代码库 > Python - 定制pattern的string模板(template) 详解
Python - 定制pattern的string模板(template) 详解
定制pattern的string模板(template) 详解
本文地址: http://blog.csdn.net/caroline_wendy/article/details/28625179
string.Template的pattern是一个正则表达式, 可以通过覆盖pattern属性, 定义新的正则表达式.
如: 使用新的定界符"{{", 把{{var}}作为变量语法.
代码:
# -*- 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‘))
输出:
\$(?: (?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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。