所以我有一个要求,我想用=
替换字符串中的所有==
,但是问题是字符串也可能包含!=
,我不希望{{ 1}}或=
被替换。
因此,仅用!=
替换=
是行不通的,我在想是否有一种方法可以检查==
在替换之前是否没有=
。
我在寻找正则表达式,但这似乎无法解决问题。
答案 0 :(得分:0)
使用replace:
test = "Hey this is a == test where != or = should not be changed"
print(test.replace("==", "="))
输出:
Hey this is a = test where != or = should not be changed
OR
import re
replaced = re.sub('==', '=', test)
print(replaced)
编辑:
您需要的是:
(?<!a)b matches a "b" that is not preceded by an "a",
=
的正则表达式,其中=
之前没有=
:
test = "Hey this is a = test where != or = should not be changed"
import re
print(re.findall(r'(?<!!)=', test))