代码之家  ›  专栏  ›  技术社区  ›  Peter Graham

如何在Python中替换成正则表达式组

  •  7
  • Peter Graham  · 技术社区  · 15 年前
    >>> s = 'foo: "apples", bar: "oranges"'
    >>> pattern = 'foo: "(.*)"'
    

    我希望能够像这样加入这个团队:

    >>> re.sub(pattern, 'pears', s, group=1)
    'foo: "pears", bar: "oranges"'
    

    有什么好办法吗?

    2 回复  |  直到 15 年前
        1
  •  10
  •   Michał Niklas    15 年前

    对我来说,工作方式如下:

    rx = re.compile(r'(foo: ")(.*?)(".*)')
    s_new = rx.sub(r'\g<1>pears\g<3>', s)
    print(s_new)
    

    通知 ? 在Re中,它以第一个结尾 " 也注意 在第1组和第3组中,因为它们必须处于输出状态。

    而不是 \g<1> (或) \g<number> )你可以只用 \1 但是记住要使用“原始”字符串 g<1> 因为 1 可能不明确(请在 Python doc )

        2
  •  0
  •   Community CDub    8 年前
    re.sub(r'(?<=foo: ")[^"]+(?=")', 'pears', s)
    

    regex匹配一系列字符

    • 跟随字符串 foo: " ,
    • 不包含双引号和
    • 其次是 "

    (?<=) (?=) lookbehind and lookahead

    如果 foo 包含转义引用。也可以使用以下方法捕获它们:

    re.sub(r'(?<=foo: ")(\\"|[^"])+(?=")', 'pears', s)
    

    样例代码

    >>> s = 'foo: "apples \\\"and\\\" more apples", bar: "oranges"'
    >>> print s
    foo: "apples \"and\" more apples", bar: "oranges"
    >>> print   re.sub(r'(?<=foo: ")(\\"|[^"])+(?=")', 'pears', s)
    foo: "pears", bar: "oranges"