首页 > 解决方案 > 如何在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但不确定具体如何。

标签: pythonregex

解决方案


可以遍历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']

推荐阅读