正则表达式替换:跳过引号内的文本 (Python)

Regex replace: skip text inside quotes (Python)

我正在尝试用 = 替换所有 : 除了引号内的 :。换句话说:替换所有没有被“某物和某物”包围的 : 。

# input
x:123; y:"z:456"

# desired output
x=123; y="z:456"

我尝试使用负数 lookbehind/lookahead 来解决这个问题,但我无法匹配引号中 : 周围的文本,因为后视中不允许使用量词;所以这不起作用:

re.sub(r'(?<!".+?):(?!.+?")', '$')

这完全可以使用正则表达式来完成吗?

谢谢!

您可以使用带有交替的捕获组 re.sub

在捕获组 1 的回调检查中。如果存在,return。否则 return 一个 =

("[^"]*")|:

看到一个regex demo and a Python demo

import re

pattern = r'("[^"]*")|:'
s = 'x:123; y:"z:456"'

res = re.sub(pattern, lambda x: x.group(1) if x.group(1) else "=", s)
print(res)

输出

x=123; y="z:456"