首页 > 解决方案 > 如何返回与特定模式不匹配的字符串列表?

问题描述

我正在尝试从文本文件中返回与特定模式不匹配的所有结果,但我在语法上遇到了困难。

pattern is [A-Z]+\_[A-Z0-9]+\_[0-9]+\_[0-9]+\.[A-Z]{3}

尝试了以下没有成功:

'^(?![A-Z]+\_[A-Z0-9]+\_[0-9]+\_[0-9]+\.[A-Z]{3}$).*$'

r'^(?!([A-Z]+\_[A-Z0-9]+\_[0-9]+\_[0-9]+\.[A-Z]{3}).)*$'

下面是匹配模式的代码,现在我需要找到所有不匹配的条目。

pattern = r'[A-Z]+\_[A-Z0-9]+\_[0-9]+\_[0-9]+\.[A-Z]{3}'

regex1 = re.compile(pattern, flags = re.IGNORECASE)

regex1.findall(text1)

数据样本如下:

plos_annotate5_1375_1.txt plos_annotate5_1375_2.txt plos_anno%tate5_1375_3.txt plos_annotate6_1032_1.txt

第三根弦是我想拉的

标签: pythonregex-negation

解决方案


如果可以在 Python 中进行,为什么要在正则表达式中进行否定?

strings_without_rx = [s for s in the_strings if not regex1.search(s)]

如果要扫描文件行,甚至不需要全部存储,因为打开的文件是其行的可迭代:

with open("some.file") as source:
  lines_without_rx = [s for s in source if not regex1.search(s)]
# Here the file is auto-closed.

推荐阅读