简体   繁体   English

正则表达式 python re.sub

[英]Regular expression python re.sub

Following are three reqular expressions with slight modifications.以下是三个经过轻微修改的正则表达式。 Can anyone explain the difference?谁能解释一下区别?

# 1.
print(re.sub(r"a(\d{4})","A\1","a2134"))
# Output-->A.

# 2.
print(re.sub(r"a(\d{4})","A","a2134"))
# Output-->A

# 3.
print(re.sub(r"a(\d{4})",r"A\1","a2134"))
# Output-->A2134

In the first example you didn't use raw string.在第一个示例中,您没有使用原始字符串。 That means that you replaced your string with A\\x01 (print '\\1' outputs \\x01) so that's the output you should see In the third example you used raw string.这意味着您将字符串替换为 A\\x01(打印 '\\1' 输出 \\x01),因此您应该看到的输出是在第三个示例中您使用了原始字符串。 That means that re.sub received A\\1 ( and not \\x01) as it's input and it replaces \\1 with the first group that it found in the source string The second example isn't really related.这意味着 re.sub 接收到 A\\1 (而不是 \\x01)作为它的输入,并且它将 \\1 替换为它在源字符串中找到的第一组第二个示例并没有真正相关。 You just replace your string with A你只需用 A 替换你的字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM