如何在Lua中从特定内容的行中读取到另一个特定内容的行?

在LUA中,我需要从特定内容的行开始读取文本文件,直到另一个特定内容的行。 请问我该如何做?

以下是一个示例

一个名为aaa.txt的文本文件

...
...
...
[Main from here on]
line1
line2
line3
...
...
title=Till here
...
...

因此,我需要从方括号行 \ [Main from here on](已命名)开始计算行数,直到最后一行称为 "title=Till here"

点赞
用户6632736
用户6632736

这个解决方案基于 io.lines () 迭代器

--[[
    这个函数会返回从 <file> 中 <from> 到 <to> 或文件末尾包含两端的所有行。
--]]
local function readFromTo (file, from, to)
    io.input (file) -- 打开文件。
    local started = false
    local lines = {}
    for line in io.lines () do
        if not started and line == from then
            started = true
        end
        if started then
            lines [#lines + 1] = line
            if line == to then
                -- 找到 <to>:
                return lines
            end
        end
    end
    -- 仅当找不到 <to> 时:
    return lines
end

print (table.concat (readFromTo ('aaa.txt', '[Main from here on]', 'title=Till here'), '\n'))
2021-03-02 11:09:36