python - 通过正则表达式替换字符串,同时排除带引号的字符串
问题描述
我搜索了一下,但找不到任何解决我问题的问题。对不起,如果我的问题是重复的。我正在尝试编辑 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."'
这个例子只是为了帮助理解这个问题。我正在寻找适用于一般情况的答案。
解决方案
您可以分两步完成:首先向字符添加空间,在它们之前没有空间,然后在它们之后没有空间:
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."
推荐阅读
- html - Twitter Card 验证失败 - 为什么它没有获取任何标签
- c# - 如何使用动态成员创建动态类
- xamarin.forms - Xamarin Form - 如何在 UWP 中为 MyToolkit.Controls.DataGrid 设置样式
- python - Firefox、Selenium、Webdriver:如何以编程方式清除所有 cookie 和站点数据?
- sql-server - 无法拖放表以进行查询(SQL Server)
- python - 如何将单元格公式复制到上面的 1 行,但引用新行的数据(而不是前一行的数据)
- javascript - 无法使用 replaceWith() 将值绑定到工具提示
- apache-flink - 过滤apache flink中的唯一事件
- scrapy - 在scrapy管道中访问蜘蛛属性好吗?
- reactjs - 无法读取未定义的属性“地图”,因为减速器有问题