各位用户为了找寻关于Python 中开发pattern的string模板(template) 实例详解的资料费劲了很多周折。这里教程网为您整理了关于Python 中开发pattern的string模板(template) 实例详解的相关资料,仅供查阅,以下为您介绍关于Python 中开发pattern的string模板(template) 实例详解的详细内容
定制pattern的string模板(template) 详解
string.Template的pattern是一个正则表达式, 可以通过覆盖pattern属性, 定义新的正则表达式.
如: 使用新的定界符"{{", 把{{var}}作为变量语法.
代码:
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33# -*- 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'
))
输出:
? 1 2 3 4 5 6 7 8 9 10 11
$(?:
(?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
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://blog.csdn.net/caroline_wendy/article/details/28625179