【问题标题】:How to find lines which do not match a list of patterns?如何查找与模式列表不匹配的行?
【发布时间】:2016-03-14 08:16:19
【问题描述】:

我想在文档中查找与模式列表不匹配的所有非空行。例如,在下面的文档 sn-p 中,我想要一个匹配行号 2、4、5、6、18、19、20 和 21 的正则表达式。

我想排除类似于 8、10、12、14、16 的行以及所有空行。

相反的模式是(?i)^.*02 December_|^\s*Python Proprietary|^\s*Python Regular Expression Specification|^.*page\s+\d+|^\s*$。我想要一个匹配所有与上述模式不匹配的行的模式。

 1:
 2:This module provides regular expression matching operations.
 3:
 4:Regular expressions use the backslash character ('\') to indicate special forms
 5:or to allow special characters to be used without invoking their special
 6:meaning.
 7:
 8:Python Regular Expression                                           02 December 1999 
 9:
10:                                                                 Python Proprietary 
11:
12:----------------------- Page 292-----------------------
13:
14:PYTHON RE SPECIFICATION Version 2.7 [Vol 9, Part Q]                     page 983 
15:
16:Python Regular Expression Specification 
17:
18:It is important to note that most regular expression operations are available as
19:module-level functions and RegexObject methods. The functions are shortcuts that
20:don’t require you to compile a regex object first, but miss some fine-tuning
21:parameters.
22:

附: -

  1. 我正在使用 re.match()。
  2. 实际文档的每行开头没有行号。为了便于讨论,已在此 sn-p 中添加了行号。

【问题讨论】:

  • 只匹配你拥有的行有什么问题,跟踪那些不匹配的行。
  • 是否有特定原因导致您无法反转匹配,并让您的代码返回除匹配行之外的所有行?
  • @PiëtDelport - 我可以,但这会改变现有更大程序的流程。如果我在这里找不到好的答案,那么这正是我要做的。
  • 你能解释一下上下文吗?这将有助于制定答案。
  • @PiëtDelport - 这是文档解析器的一部分,我正在修改的解析器部分现在遵循格式 - 匹配一个模式,如果匹配成功,则执行相应的操作 .

标签: python regex python-2.7 regex-negation


【解决方案1】:

您可以使用否定的前瞻性:

正则表达式

^(?i)(?!-+\s+Page\s+\d+-+|Python\s+Regular\s+Expression\s+\d{2}.+\d{4}|.+Python\s+Proprietary|PYTHON\s+RE SPECIFICATION\s+Version.+\s+page\s+\d+|Python\s+Regular\s+Expression\s+Specification).+$

演示

Click to view

说明

【讨论】:

    【解决方案2】:

    试试这个

    ^.*?Python Regular Expression.*?$(*SKIP)(*FAIL)|^.*?Python Proprietary.*?$(*SKIP)(*FAIL)|.*?Page \d+.*?$(*SKIP)(*FAIL)|^$(*SKIP)(*FAIL)|^.*?$
    

    Demo

    结果:

    匹配 8 行 2、4、5、6、18、19、20 和 21。

    解释:

    ^.*?Python Regular Expression.*?$(*SKIP)(*FAIL) 排除第 6、16 行。
    ^.*?Python Proprietary.*?$(*SKIP)(*FAIL) 排除第 10 行。
    .*?Page \d+.*?$(*SKIP)(*FAIL) 排除第 12、14 行。
    ^$(*SKIP)(*FAIL) 排除所有空行。
    @987654327 @ 匹配所有其他行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-03
      • 1970-01-01
      • 2018-07-20
      • 1970-01-01
      • 2014-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多