Python string templates of template examples for pattern development

  • 2020-05-27 06:25:46
  • OfStack

Customize pattern's string templates (template) for details

pattern of string.Template is a regular expression that can be defined by overwriting the pattern property.

For example, use the new delimiter "{{" and use {{var}} as the variable syntax.

Code:


# -*- 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')) 

Output:


  \$(?: 
   (?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 

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: