【问题标题】:Python Regex - Different Results in findall and subPython Regex - findall 和 sub 中的不同结果
【发布时间】:2014-12-11 18:26:06
【问题描述】:

我正在尝试将出现的工作“早午餐”替换为“早午餐”。我正在使用正确识别事件的正则表达式,但是当我尝试使用 re.sub 时,它替换的文本多于 re.findall 识别的文本。我正在使用的正则表达式是:

re.compile(r'(?:^|\.)(?![^.]*saturday)(?![^.]*sunday)(?![^.]*weekend)[^.]*(brunch)',re.IGNORECASE)

字符串是

str = 'Valid only for dine-in January 2 - March 31, 2015. Excludes brunch, happy hour, holidays, and February 13 - 15, 2015.'

我希望它产生:

'Valid only for dine-in January 2 - March 31, 2015. Excludes BRUNCH, happy hour, holidays, and February 13 - 15, 2015.'

步骤:

>>> reg.findall(str)
>>> ['brunch']
>>> reg.sub('BRUNCH',str)
>>> Valid only for dine-in January 2 - March 31, 2015BRUNCH, happy hour, holidays, and February 13 - 15, 2015.

编辑:

我使用的最终解决方案是:

re.compile(r'((?:^|\.))(?![^.]*saturday)(?![^.]*sunday)(?![^.]*weekend)([^.]*)(brunch)',re.IGNORECASE)
re.sub('\g<1>\g<2>BRUNCH',str)

【问题讨论】:

    标签: python regex


    【解决方案1】:

    对于re.sub 使用

    (^|\.)(?![^.]*saturday)(?![^.]*sunday)(?![^.]*weekend)([^.]*)(brunch)
    

    替换为\1\2BRUNCH。查看演示。

    https://regex101.com/r/eZ0yP4/16

    【讨论】:

    • 唯一的问题是它删除了句号。
    • re.sub 在这种情况下效果更好,因为它是规范化文本的正则表达式列表的一部分。并非所有替换都如此简单。此外,如果该词多次出现但在不同的上下文中,您可能只想替换正确的。
    • @AvinashRaj OP 在他之前的问题中询问了正则表达式。请检查一下。我已经回答了这个问题。stackoverflow.com/questions/27398870/…
    【解决方案2】:

    通过正则表达式:

    (^|\.)(?![^.]*saturday)(?![^.]*sunday)(?![^.]*weekend)([^.]*)brunch
    

    DEMO

    将匹配的字符替换为\1\2BRUNCH

    【讨论】:

      【解决方案3】:

      为什么匹配的次数超过brunch

      因为你的正则表达式实际上比早午餐更匹配

      See link on how the regex match

      为什么findall不显示?

      因为您只在括号中包裹了brunch

      >>> reg = re.compile(r'(?:^|\.)(?![^.]*saturday)(?![^.]*sunday)(?![^.]*weekend)[^.]*(brunch)',re.IGNORECASE)
      >>> reg.findall(str)
      ['brunch']
      

      在括号中包裹整个([^.]*brunch)之后

      >>> reg = re.compile(r'(?:^|\.)(?![^.]*saturday)(?![^.]*sunday)(?![^.]*weekend)([^.]*brunch)',re.IGNORECASE)
      >>> reg.findall(str)
      [' Excludes brunch']
      
      • re.findall 忽略那些未被捕获的

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多