python - 在这种情况下我应该使用什么正则表达式?
问题描述
我想创建一个正则表达式以仅获取以日期开头的行(忽略其他行)以及上面带有“前缀”一词的行。正则表达式应该如何?
我的 txt 文件中有以下结构:
Prefix : 0051601
Data Material No. OS Hist. Nr/Controle Quant. Vlr.Unit. Vlr.Total
----------------------------------------------------------------------------------------------------------------------------------------
13/01/2008 00101050 Lampada farol H5 24V 003 4863 2,000 9,870556 19,7411
====== Total dia 13/01/2008 ======
Entradas :
Saídas : 2,000 19,7411
-------------------------------------------------------------------
主要代码是:
import glob, os
import re
os.chdir("./txtfiles/")
for file in glob.glob("*.txt"):
with open(file) as f:
content = f.readlines()
# not working, just for test purpose
result = re.match(r'Prefix', content, re.M|re.I)
if result:
print(content)
else:
print "no match found!"
解决方案
您可以使用此正则表达式来识别这些行。
使用 findall 获取所有行。
r"(?im)(?:^[^\S\r\n]*\d+/\d+/\d+|.*\bprefix).*"
推荐阅读
- python - 在分类列和数值列中一次替换缺失值
- laravel - Laravel 或 MySQL 正确的词
- python - Django模型保存两次
- ios - 从 '[[AnyHashable : Any]]' 转换为不相关的类型 '[AnyHashable : Any]' 总是失败
- android - Firebase android从表中获取所有内容
- docker - 如何禁用正在运行的 Docker 容器的网络?
- ios - 如何使用 Eureka 将单元格添加到 UITableViewController?
- javascript - 由于默认情况下未启用严格模式,如何在 Chrome 开发工具中访问“让”关键字?
- python - 在python中递归退出矩形
- automapper - 使用 AutoMapper 在 .NET Core 中找不到 AddAutoMapper