【问题标题】:Regex replace: skip text inside quotes (Python) [duplicate]正则表达式替换:跳过引号内的文本(Python)[重复]
【发布时间】:2021-09-02 05:14:31
【问题描述】:

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

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

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

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

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

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

谢谢!

【问题讨论】:

    标签: python regex regex-lookarounds lookbehind


    【解决方案1】:

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

    在回调中检查捕获组 1。如果存在,则返回它。否则返回=

    ("[^"]*")|:
    

    查看regex demoPython 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"
    

    【讨论】:

    • 冷却解决方案。为我工作。谢谢!顺便说一句:对于其他对此感兴趣的人:实际上讨论了一个类似的用例here(我最初没有找到)。
    猜你喜欢
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 2020-06-07
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多