首页 > 解决方案 > 通过正则表达式替换字符串,同时排除带引号的字符串

问题描述

我搜索了一下,但找不到任何解决我问题的问题。对不起,如果我的问题是重复的。我正在尝试编辑 python 代码来替换所有 -/+/= 两边都没有空格的运算符。

string = 'new_str=str+"this is a quoted string-having some operators+=- within the code."'

我会使用 '([^\s])(=|+|-)([^\s])' 来查找此类运算符。问题是,我想在引用的字符串中排除这些发现。有没有办法通过正则表达式替换来做到这一点。我想要得到的输出是:

edited_string = 'new_str = str + "this is a quoted string-having some operators+=- within the code."'

这个例子只是为了帮助理解这个问题。我正在寻找适用于一般情况的答案。

标签: pythonreplacere

解决方案


您可以分两步完成:首先向字符添加空间,在它们之前没有空间,然后在它们之后没有空间:

string = 'new_str=str+"this is a quoted string-having some operators+=- within the code."'

new_string = re.sub("(?<!\s>)(\+|\=)[^\+=-]", r" \g<0>", string)
new_string = re.sub("(\+|\=)(?=[^\s|=|-])", r"\g<0> ", new_string)
print(new_string)
>>> new_str = str + "this is a quoted string-having some operators+=- within the code."

推荐阅读