【问题标题】:How to match/search for a specific pattern but not having another specific pattern?如何匹配/搜索特定模式但没有另一个特定模式?
【发布时间】:2021-04-21 19:49:40
【问题描述】:

我需要匹配更大字符串中的模式not check

bigger_string = '<some words and> do not check <some other words>'

但后面不应该有数字。所以,not check &lt;some words&gt; 应该匹配,但 not check 67 &lt;some words&gt; 不应该匹配。 我试过这些:

re.findall(re.compile(r'not\s*check\s*\D*', re.I), bigger_string)

re.findall(re.compile(r'not\s*check\s*[^0-9]*', re.I), bigger_string)

它不起作用。这总是返回一个匹配项。

【问题讨论】:

  • 试试:r'\bnot\s+check(?!\s*\d)'
  • \bnot check\b[^\d\n]*$,如果在字符串结尾之前不应再有任何数字。
  • 感谢@anubhava 和@the。我尝试了类似的模式\s*(?!\d)。它也没有用。你的和我的有什么区别?
  • 使用 regex101.com 查看正则表达式是如何匹配的。
  • 区别在于\s*可以匹配一个零长度的字符串。所以它回溯并匹配not check,后跟零个空格。由于后面没有数字,因此模式匹配。

标签: python python-3.x regex


【解决方案1】:

not\s*check\s*\D* 中的\D* 表示匹配第一个数字,而不是如果前面没有数字则只匹配

使用

\bnot\s+check\b(?!\s*\d)\D*

proof

解释

--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char
--------------------------------------------------------------------------------
  not                      'not'
--------------------------------------------------------------------------------
  \s+                      whitespace (\n, \r, \t, \f, and " ") (1 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  check                    'check'
--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    \s*                      whitespace (\n, \r, \t, \f, and " ") (0
                             or more times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
    \d                       digits (0-9)
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  \D*                      non-digits (all but 0-9) (0 or more times
                           (matching the most amount possible))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    • 2015-09-10
    • 2021-11-04
    相关资源
    最近更新 更多