【问题标题】:regex for excluding certain phrase from txt.file用于从 txt.file 中排除某些短语的正则表达式
【发布时间】:2021-02-19 14:47:12
【问题描述】:

我需要从看起来像 +/- 的 txt 文件中检索数字:

[  Index 1  ]
1628 5704
32801 61605
71508 90612
1026061

我需要忽略 Indexe 的号码。

[0-9]+ 检索所有数字,以及索引。

我尝试了类似这样的方法,称为负前瞻(?![(Index 1)])([0-9]+)。它确实忽略了 1,但所有这些……例如 1628 变为 628。感谢帮助,我在正则表达式语法方面一直很弱:/

【问题讨论】:

  • 如果你不希望括号内的数字,你可以检查if there is not a closing ] ahead
  • 对你想要的东西非常模糊,举一个带有多个索引和所需输出的示例输入

标签: python regex re


【解决方案1】:

使用

\b(?<!Index )\d+

proof

说明

--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char
--------------------------------------------------------------------------------
  (?<!                     look behind to see if there is not:
--------------------------------------------------------------------------------
    Index                    'Index '
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  \d+                      digits (0-9) (1 or more times (matching
                           the most amount possible))

【讨论】:

    【解决方案2】:

    这个模式只匹配数字。它在字符串或序列的开头寻找一个系列或多个数字,或在一个字符串的末尾寻找多个数字。

    ^\d+|\d+$
    

    https://regex101.com/r/ZNTxQ7/1

    另一种方法是在字符串中查找一系列两个或多个数字。

    \d{2,}
    

    https://regex101.com/r/Di75KT/1

    【讨论】:

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