[英]replace string via re.sub() using a regular expression as replacer
string = "@ABlue , @Red , @GYellow, @Yellow, @GGreen"
new = re.sub('(@[A-Z][A-Z])', "########" , string)
我需要一个正则表达式,它可以检查两个大写字母后面的@,然后删除@和第一个大写字符.cc
使用捕获组和反向引用:
>>> import re
>>> string = "@ABlue , @Red , @GYellow, @Yellow, @GGreen"
>>> re.sub('@[A-Z]([A-Z])', r"\1" , string)
'Blue , @Red , Yellow, @Yellow, Green'
替换字符串中的\\1
将被第一个捕获组(第二个大写字母)替换。
注意使用了r"raw string literal"
。 否则,您需要转义\\
: "\\\\1"
使用正向超前断言的替代方法:
>>> re.sub('@[A-Z](?=[A-Z])', '' , string)
'Blue , @Red , Yellow, @Yellow, Green'
>>> new = re.sub(r"@[A-Z]([A-Z])", r"\1" , string)
>>> new
'Blue , @Red , Yellow, @Yellow, Green'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.