Python 中開發pattern的string模板(template) 例項詳解

NO IMAGE

定製pattern的string模板(template) 詳解

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 

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支援!

您可能感興趣的文章:

java 中InputStream,String,File之間的相互轉化對比Python 基礎之字串string詳解及例項js中toString()和String()區別詳解List呼叫toString()方法後,去除兩頭的中括號例項python實現字典(dict)和字串(string)的相互轉換方法String類下compareTo()與compare()方法比較