Python - 定制pattern的string模板(template) 具体解释

定制pattern的string模板(template) 具体解释

本文地址: http://blog.csdn.net/caroline_wendy/article/details/28625179

string.Templatepattern是一个正則表達式, 能够通过覆盖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

Python - 定制pattern的string模板(template) 具体解释

上一篇:QT模态对话框用法(在UI文件中设置Widget背景图,这个图是一个带阴影边框的图片——酷)


下一篇:FLINK SQL Calcite原理