python - 为什么\g<0> 在 re.sub 中的行为与\0 不同?

标签 python regex

我正在使用 Python 3.3

re.sub("(.)(.)",r"\2\1\g<0>","ab")  returns baab

但是

re.sub("(.)(.)",r"\2\1\0","ab")  returns ba

这是 sub 方法中的错误还是 sub 方法出于某种原因故意不识别\0?

最佳答案

作为written on this page\0 在 Python 中被解释为空字符 (\x00) 和组号从 1 开始(根据 re 模块文档):

\number

Matches the contents of the group of the same number. Groups are numbered starting from 1. For example, (.+) \1 matches 'the the' or '55 55', but not 'thethe' (note the space after the group). This special sequence can only be used to match one of the first 99 groups. If the first digit of number is 0, or number is 3 octal digits long, it will not be interpreted as a group match, but as the character with octal value number. Inside the '[' and ']' of a character class, all numeric escapes are treated as characters.

此外,根据之前链接的页面,这不是错误而是期望的行为(这是显而易见的,因为它已记录在案)。

关于python - 为什么\g<0> 在 re.sub 中的行为与\0 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21028917/

相关文章:

c# - 正则表达式在同一输入上返回不同的结果

python - 使用新的 "virtual"列保存基于类的 View 表单集项

python - 属性值中不允许使用未转义的 '<'

c# - 验证部分邮件后缀

regex - 如何在 RStudio 中查找并替换行尾

c# - 正则表达式 if 条件 c#

python - 如何将多个 Cython pyx 文件合并到一个链接库中?

python - 值错误: Invalid frequency when resampling

python - Python 中的 slice() 函数有什么作用?

java - Groovy 正则表达式不起作用