python - 将“Python 模板字符串”扩展为非 ASCII
问题描述
我正在尝试使用Python Template Strings填充公式字符串中的值。该公式有时包含具有非 ASCII 字符的标识符,例如 α、ß、Γ 等(参见Unicode Greek 和 Coptic Chart)。但根据 python 文档,模板字符串仅限于 ASCII 标识符。与标识符匹配的默认正则表达式是(?a:[_a-z][_a-z0-9]*)
.
如何扩展默认正则表达式,使其也匹配Unicode Greek 和 Coptic Chart中的字符?
解决方案
这就是我能够解决我的问题的方法。
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
是固定的,如果在后期更改则无效。
推荐阅读
- c++ - 这是真正具有最小阻塞的线程安全 LRU 缓存设计吗?
- php - PHP - 寻找在嵌套数组项之前添加特定键的更好方法
- javascript - Discord.js:如何检查特定用户是否具有角色?
- python - 在索引日期列(lte)上过滤数据框
- java - 等待 JavaFX 运行时准备好
- amazon-web-services - 如果令牌来自 Cognito,HttpActionContext 如何从 Jwt 令牌获取 ClaimsPrincipal
- telegram - Telegram Bot 适用于其他帐户,但不适用于我的帐户
- encryption - 如何在lua中加密RSA?
- marklogic - 根据 Marklogic 中的最大匹配词增加分数
- javascript - React-bootstrap-table2:我如何编辑单元格内的数组