python - 如何在Python中使用正则表达式查找匹配字符串到特定字符串
问题描述
我需要在文件中找到特定的字符串AUTO HEADER
。我不确定如何将regex
匹配项限制为仅查找特定行。有人可以帮我弄清楚吗?
这是我的脚本:
import re
a = open("mod.txt", "r").read()
op = re.findall(r"type=(\w+)", a, re.MULTILINE)
print(op)
这是我的输入文件 mod.txt:
bla bla bla
header
module a
(
type=bye
type=junk
name=xyz type=getme
type=new
AUTO HEADER
type=dont_take_it
type=junk
type=new
输出:
['bye', 'junk', 'getme', 'new', 'dont_take_it', 'junk', 'new']
预期输出:
['bye', 'junk', 'getme', 'new']
在regex
中,我需要考虑AUTO HEADER
但不确定具体如何。
解决方案
可以遍历txt文件中的每一行,找到需要的key就退出
前任:
import re
res = []
with open(filename) as infile:
for line in infile:
if "AUTO HEADER" in line:
break
op = re.search(r"type=(\w+)", line)
if op:
res.append(op.group(1))
print(res) # --> ['bye', 'junk', 'getme', 'new']
推荐阅读
- map-matching - 使用不同的方式操作地图?
- r - Rstudio:为什么适合统计的 M2 适用于四个分级响应模型中的单个案例?
- android - 应用程序关闭时的定期任务和通知
- iot - 累积数据类型处理
- javascript - 在 JavaScript 画布 API 中设置允许的绘图区域
- azure-active-directory - 尽管权限正确,Microsoft Graph 用户/getMemberGroups 仍失败
- java - WildFly 启动中的 java.net.UnknownHostException
- python - pandas apply() 函数对于 Python requests() 的安全性如何?
- c++ - 静态链接启用 PIC 构建的库时出现链接器 PIC 错误
- oracle - 如何在没有附件的情况下导出oracle查询结果