python - 如何返回与特定模式不匹配的字符串列表?
问题描述
我正在尝试从文本文件中返回与特定模式不匹配的所有结果,但我在语法上遇到了困难。
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
第三根弦是我想拉的
解决方案
如果可以在 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.
推荐阅读
- swift - 设置一次并清除后选择器未正确填充
- javascript - javascript数组 - 如何过滤一个嵌套级别并仅获取该值
- google-analytics - 如何跟踪 next.js 项目中的初始页面浏览量?
- header - 是否有我们可以添加到 gempages (shopify) 以创建标题而不必处理 shopify 的应用程序?
- wordpress - 如何显示内联 form_fields 的复选框 - Wordpress 设置 API 开发
- javascript - 我的视频模式在加载页面上显示为空白,我该如何纠正?
- html - 为什么 ASP.NET Core MinLength 属性没有添加 HTML minlength 属性,而 MaxLength 有?
- c - m68k-elf 目标是否支持 GCC 内联 asm goto?
- protractor - 量角器中的 ARROW_DOWN
- eslint - 如何禁止 Prettier 修改标签