gpt4 book ai didi

python - python re.template 函数有什么作用?

转载 作者:太空狗 更新时间:2023-10-29 18:04:04 50 4
gpt4 key购买 nike

在 ipython 中使用 re 模块时,我注意到一个未记录的 template 函数:

In [420]: re.template?
Type: function
Base Class: <type 'function'>
String Form: <function template at 0xb7eb8e64>
Namespace: Interactive
File: /usr/tideway/lib/python2.7/re.py
Definition: re.template(pattern, flags=0)
Docstring:
Compile a template pattern, returning a pattern object

还有一个标志 re.TEMPLATE 及其别名 re.T

2.7 或 3.2 的文档中均未提及这些内容。他们在做什么?它们是早期 Python 版本的遗留问题,还是 future 可能正式添加的实验性功能?

最佳答案

在 CPython 2.7.1 中,re.template() is defined作为:

def template(pattern, flags=0):
"Compile a template pattern, returning a pattern object"
return _compile(pattern, flags|T)

_compile 调用 _compile_typed,后者调用 sre_compile.compile。代码中唯一检查 T(又名 SRE_FLAG_TEMPLATE)标志的地方是 in that function :

    elif op in REPEATING_CODES:
if flags & SRE_FLAG_TEMPLATE:
raise error, "internal: unsupported template operator"
emit(OPCODES[REPEAT])
skip = _len(code); emit(0)
emit(av[0])
emit(av[1])
_compile(code, av[2], flags)
emit(OPCODES[SUCCESS])
code[skip] = _len(code) - skip
...

这会产生禁用所有重复运算符的效果(*+?{}等):

In [10]: re.template('a?')
---------------------------------------------------------------------------
.....
error: internal: unsupported template operator

代码的结构方式(无条件的 raise 在一堆死代码之前)让我认为该功能要么从未完全实现,要么由于某些问题而被关闭。我只能猜测预期的语义可能是什么。

最终结果是该函数没有做任何有用的事情。

关于python - python re.template 函数有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7677889/

50 4 0