我正在使用 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/