Python 3
I have recently started reading regex
and consider the following case :
If input is AB
followed by C
or D
i want to replace it with EF
So, my char class
is [CD]
and it should be non-capturing
.
Using the re.sub
i come up with the following:
re.sub(r'AB(?:[CD])','EF',text)
When i run this code for input ABCZ i get EFZ
Thanks!
Non-capturing doesn't mean it's not included in the match. It just means it's not captured as a group (so you can't use backreferences like \\1
to refer to it).
If you want to specify that [CD]
should follow but not be included in the match, you need to use a lookahead:
>>> re.sub(r'AB(?=[CD])','EF','ABCZ')
'EFCZ'
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.