【问题标题】:how to avoid regex matching "Revert "Revert"如何避免正则表达式匹配“Revert”“Revert”
【发布时间】:2019-02-03 01:22:54
【问题描述】:

我有以下代码同时匹配第 1 行和第 2 行,我想匹配第 2 行但不匹配第 1 行,谁能提供有关如何执行此操作的指导?

import re   

line1 = '''Revert "Revert <change://problem/47614601> [tech feature][V3 Driver] Last data path activity timestamp update is required for feature""'''
line2 = '''Revert <change://problem/47614601> [tech feature][V3 Driver] Last data path activity timestamp update is required for feature"'''

if re.findall(".*?(?:Revert|revert)\s*\S*(?:change:\/\/problem\/)(\d{8})", line2):
    match = re.findall(".*?(?:Revert|revert)\s*\S*(?:change:\/\/problem\/)(\d{8})", line2)
    print "Revert radar match%s"%match
    revert_radar = True

print revert_radar

【问题讨论】:

  • line.startswith('Revert'} and line.count('Revert') == 1?
  • 不,这不适用于所有其他情况,我需要修复正则表达式,因为它也可以处理其他情况
  • 可能在开头使用否定前瞻断言来排除不需要的行。
  • 所有 unwanted 案例的结构是否相同? word your looking for followed by a space followed by a double quote and the same word?
  • 它们是单独的行还是更大的正文中的行?

标签: python


【解决方案1】:

这样的事情应该做你想做的事:

>>> regex = "(?!:(?:R|r)evert.*)(?:Revert|revert)\s*\S*(?:change:\/\/problem\/)(\d{8})"
>>> re.match(regex, line1) is None
True
>>> re.match(regex, line2).groups()
('47614601',)

【讨论】:

    【解决方案2】:

    否定的看后面:单词 NOT 由 sameword-space-doublequote 进行

    r'''(?<![Rr]evert ")[Rr]evert\s<change:[/][/]problem[/]\d{8}.*"'''
    

    负面展望:你不想跟双引号的模式

    r'''[Rr]evert\s<change:[/][/]problem[/]\d{8}.*?\w"(?!")'''
    
    • 如果 unwanted 行直接位于所需行之前且没有插入换行符,则此方法不起作用。
    • 如果 unwanted 行跟在所需行之后,它确实有效。

    如果查看单个行,请查找字符串开头的模式 - 在三行中,这是最少的工作,对正则表达式引擎最有效

    r'''^[Rr]evert\s<change:[/][/]problem[/]\d{8}.*$'''
    

    如果您要搜索的行嵌入在一个长字符串中,但在该行之前有一个换行符,您可以使用带有多行标志的前一个模式。

    【讨论】:

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