在Lua中获取2条特定线之间的线

时间:2015-12-14 15:13:07

标签: io lua

使用io.open读取文件,现在我尝试在其他2行之间获取特定行。

文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<somethings>
    <something attribute="some" />
    <something attribute="some1" />
</somethings>

我希望在表格中存储<somethings></somethings>之间的界限。到目前为止我所拥有的:

local file = io.open(file, "r")
local arr = {}

for line in file:lines() do
    table.insert(arr, line);
end

但它将所有行插入数组。

1 个答案:

答案 0 :(得分:2)

试试这个:

local collecting=false    
for line in file:lines() do
    if line:match("</somethings>") then
       collecting=false  -- or break if there is only one block
    end
    if collecting then
       table.insert(arr, line)
    end
    if line:match("<somethings>") then
       collecting=true
    end
end