1

我的模板引擎翻译

"some data #{substitution_expression} some other data"

进入

"some data" + (substitution_expression) + "some other data"

但如果“一些数据”或“一些其他数据”内部有双引号,则评估失败。我必须在这些引号之前添加斜杠,但我想不出正确的正则表达式。

有什么帮助吗?

更新:

这是模板引擎的工作方式:

  1. 它得到一个模板字符串,例如

    template = 'template string "quoted text" #{expression}'
    
  2. 它通过一个简单的正则表达式将模板字符串更改为:

    template = '"%s"' % re.compile(r'\#{(.*)}').match(r'" + (\1) + "', template)  
    # template == "template string "quoted text"" + (expression) + ""  
    # here is a problem with a "quoted text" - it needs \ before quotes`
    
  3. 这个字符串被插入到 lambda 中,并且结果代码字符串正在被评估:

    return eval("lambda tpl_args: %s" % modified_template_string)
    
  4. 稍后在程序中使用一些 tpl_args 调用 lambda 以生成结果字符串。

4

1 回答 1

1

你试过 re.DOTALL 标志吗?

re.compile(r'\#{(.*)}', re.DOTALL)
于 2012-11-27T22:19:17.323 回答