re.sub 与包含圆括号的边界和字符串一起使用时出现问题
Trouble with re.sub when used with boundary and string containing round brackets
我有以下字符串,我想用 10
替换 (abc +0.5)*3
Test_String= 'I am not able to replace (abc+0.5)*3'
我尝试了以下方法
re.sub('\b(abc\+0.5)\*3\b','10',Test_String)
re.sub('\b\(abc\+0.5\)\*3\b','10',Test_String)
但似乎没有任何效果,我正在使用边界,因为我想替换完全匹配。
预期输出
I am not able to replace 10
实际输出
I am not able to replace (abc+0.5)*3
我做错了什么?
你可以
- 不是双重转义,
\+
变成了\+
- 不使用单词边界
\b
因为左括号旁边没有单词边界(可以保留右括号)
- 转义点
\.
(可选,因为它代表任何字符)
test_string = 'I am not able to replace (abc+0.5)*3'
res = re.sub(r'\(abc\+0\.5\)\*3\b', '10', test_string) # \b is optional
print(res) # I am not able to replace 10
我有以下字符串,我想用 10
(abc +0.5)*3
Test_String= 'I am not able to replace (abc+0.5)*3'
我尝试了以下方法
re.sub('\b(abc\+0.5)\*3\b','10',Test_String)
re.sub('\b\(abc\+0.5\)\*3\b','10',Test_String)
但似乎没有任何效果,我正在使用边界,因为我想替换完全匹配。
预期输出
I am not able to replace 10
实际输出
I am not able to replace (abc+0.5)*3
我做错了什么?
你可以
- 不是双重转义,
\+
变成了\+
- 不使用单词边界
\b
因为左括号旁边没有单词边界(可以保留右括号) - 转义点
\.
(可选,因为它代表任何字符)
test_string = 'I am not able to replace (abc+0.5)*3'
res = re.sub(r'\(abc\+0\.5\)\*3\b', '10', test_string) # \b is optional
print(res) # I am not able to replace 10