【问题标题】:Regex - look-behind requires fixed-width pattern error [duplicate]正则表达式 - 后视需要固定宽度的模式错误 [重复]
【发布时间】:2020-03-19 07:44:52
【问题描述】:

代码:

text = "('hel'lo') eq 'some 'variable he're'"
re.compile(r"(?<!\(|(?<=eq ))'(?!\)|\Z)").sub(string=text, repl="''")

出现错误:

re.error: look-behind requires fixed-width pattern

预期输出

('hel''lo') eq 'some ''变量 he''re'

【问题讨论】:

    标签: python regex python-3.x


    【解决方案1】:

    如果你想断言左边不是eq ,它应该是一个否定的(?&lt;!,而不是一个积极的后视。

    您可以使用 2 个后向断言来编写模式。

    (?<!\()(?<!eq )'(?!\)|\Z)
    

    Regex demo | Python demo

    示例代码

    import re
    text = "('hel'lo') eq 'some 'variable he're'"
    print(re.compile(r"(?<!\()(?<!eq )'(?!\)|\Z)").sub(string=text, repl="''"))
    

    输出

    ('hel''lo') eq 'some ''variable he''re'
    

    【讨论】:

    • 我试图使用 ALTERNATIVES 这导致了我的错误。两个 Look behind 也有效.. 非常感谢您
    猜你喜欢
    • 2021-02-21
    • 2014-07-09
    • 2018-01-10
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    相关资源
    最近更新 更多