[英]Python Regex char class
Python 3 Python 3
I have recently started reading regex
and consider the following case : 我最近开始阅读
regex
并考虑以下情况:
If input is AB
followed by C
or D
i want to replace it with EF
如果输入是
AB
然后是C
或D
我想将其替换为EF
So, my char class
is [CD]
and it should be non-capturing
. 因此,我的
char class
是[CD]
,应该non-capturing
。
Using the re.sub
i come up with the following: 使用
re.sub
我提出了以下内容:
re.sub(r'AB(?:[CD])','EF',text)
When i run this code for input ABCZ i get EFZ 当我运行输入ABCZ这个代码我得到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). 这只是意味着它没有被捕获为一个组(因此您不能使用
\\1
类的反向引用来引用它)。
If you want to specify that [CD]
should follow but not be included in the match, you need to use a lookahead: 如果要指定
[CD]
应该跟随但不包括在比赛中,则需要使用前瞻性:
>>> re.sub(r'AB(?=[CD])','EF','ABCZ')
'EFCZ'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.