首页 > 解决方案 > 将“Python 模板字符串”扩展为非 ASCII

问题描述

我正在尝试使用Python Template Strings填充公式字符串中的值。该公式有时包含具有非 ASCII 字符的标识符,例如 α、ß、Γ 等(参见Unicode Greek 和 Coptic Chart。但根据 python 文档,模板字符串仅限于 ASCII 标识符。与标识符匹配的默认正则表达式是(?a:[_a-z][_a-z0-9]*).

如何扩展默认正则表达式,使其也匹配Unicode Greek 和 Coptic Chart中的字符?

标签: pythonpython-3.xregextemplates

解决方案


这就是我能够解决我的问题的方法。

from string import Template as _Template

    class Template(_Template):
        """Created a custom template class becasue default Template class doesn't support non ASCII identifiers"""
        idpattern = r'([_a-z\u0370-\u03FF][_a-z0-9\u0370-\u03FF]*)'

子类是必需的,因为 python 在类初始化期间编译正则表达式模式,并且默认值Template.idpattern是固定的,如果在后期更改则无效。


推荐阅读