简体   繁体   中英

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. 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. You just replace your string with A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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