Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用正则表达式作为替换程序,通过re.sub()替换字符串_Python_Regex_String - Fatal编程技术网

Python 使用正则表达式作为替换程序,通过re.sub()替换字符串

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

我需要一个正则表达式,它能够通过两个大写字母检查@,然后删除@和第一个大写字符。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"
>>> 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'