码迷,mamicode.com
首页 > 编程语言 > 详细

Python - 定制pattern的string模板(template) 详解

时间:2014-06-08 18:00:47      阅读:308      评论:0      收藏:0      [点我收藏+]

标签:mystra   python   string模板   pattern   覆盖   

定制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



bubuko.com,布布扣



Python - 定制pattern的string模板(template) 详解,布布扣,bubuko.com

Python - 定制pattern的string模板(template) 详解

标签:mystra   python   string模板   pattern   覆盖   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!