I'm using Python 3.3
我使用Python 3.3
re.sub("(.)(.)",r"
I'm using Python 3.3
我使用Python 3.3
re.sub("(.)(.)",r"\2\1\g<0>","ab") returns baab
BUT
但
re.sub("(.)(.)",r"\2\1\0","ab") returns ba
Is this a bug in the sub method or does the sub method not recognize \0 on purpose for some reason?
这是子方法中的一个bug,还是由于某些原因,子方法不能在目标上识别?
2 个解决方案
#1
9
As written on this page, the \0 is interpreted as the null character (\x00) and group number start at 1 in Python (according to the re module documentation):
如本页所示,\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.
匹配相同数目的组的内容。组从1开始编号。例如,(.+)\1匹配“the”或“5555”,但不匹配“thethe”(注意组后面的空格)。这个特殊序列只能用于匹配前99组中的一个。如果数字的第一个数字是0,或者数字是3个八进制数字,它将不会被解释为一个组匹配,而是作为一个八进制值的字符。在字符类的'和']'内部,所有数字转义都被视为字符。
Also, according to the page previously linked, it's not a bug but a desired behaviour (this is obvious, since it's documented).
而且,根据之前链接的页面,它不是一个bug,而是一个期望的行为(这是显而易见的,因为它是有文档记录的)。
#2
1
\0 is interpreted as an escape for null \x00, and re does not recognize it as a capture group.
\0被解释为空\x00的转义,re不承认它是一个捕获组。
Reference:
参考:
Python Standard Library documentation
Python标准库的文档
\g<0>","ab") returns baab
re.sub("