python template idpattern_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\{\{) | # Escape sequence of two delimiters

(?

P[_a-z][_a-z0-9]*)\}\} | # delimiter and a Python identifier

{(?P[_a-z][_a-z0-9]*)}\}\} | # delimiter and a braced identifier

(?P) # Other ill-formed delimiter exprs

)

'''

t2 = MyTemplate('''

{{{{

{{var}}

''')

print('MATCHES: ', t2.pattern.findall(t2.template))

print('SUBSTITUTED: ', t2.safe_substitute(var='replacement'))

输出:

\$(?:

(?P\$) | # Escape sequence of two delimiters

(?P[_a-z][_a-z0-9]*) | # delimiter and a Python identifier

{(?P[_a-z][_a-z0-9]*)} | # delimiter and a braced identifier

(?P) # Other ill-formed delimiter exprs

)

MATCHES: [('{{', '', '', ''), ('', 'var', '', '')]

SUBSTITUTED:

{{

replacement

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值