Python 使用正则表达式作为替换程序,通过re.sub()替换字符串
我需要一个正则表达式,它能够通过两个大写字母检查@,然后删除@和第一个大写字符。cc使用捕获组和反向引用:Python 使用正则表达式作为替换程序,通过re.sub()替换字符串,python,regex,string,Python,Regex,String,我需要一个正则表达式,它能够通过两个大写字母检查@,然后删除@和第一个大写字符。cc使用捕获组和反向引用: string = "@ABlue , @Red , @GYellow, @Yellow, @GGreen" new = re.sub('(@[A-Z][A-Z])', "########" , string) 替换字符串中的\1将替换为第一个捕获组(第二个大写字母) 注意使用了r“原始字符串文字”。否则,您需要转义\:“\\1” 替代使用: >>> import re
string = "@ABlue , @Red , @GYellow, @Yellow, @GGreen"
new = re.sub('(@[A-Z][A-Z])', "########" , string)
替换字符串中的\1
将替换为第一个捕获组(第二个大写字母)
注意使用了r“原始字符串文字”
。否则,您需要转义\
:“\\1”
替代使用:
>>> import re
>>> string = "@ABlue , @Red , @GYellow, @Yellow, @GGreen"
>>> re.sub('@[A-Z]([A-Z])', r"\1" , string)
'Blue , @Red , Yellow, @Yellow, Green'
>>> 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'