You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Lua中提取字符串中包含指定文本的行?

Lua实现类似grep提取包含特定文本的行

要从多行字符串中提取包含指定文本的行,可以通过按行遍历字符串+匹配校验的方式实现,以下是两种实用方案:

方案一:自定义遍历筛选函数

这是最直观的实现方式,通过string.gmatch分割每行,再检查每行是否包含目标文本:

local function grep(str, target)
    local output = ""
    -- 遍历所有行,兼容\n和\r\n换行格式
    for line in str:gmatch("[^\r\n]+") do
        if line:find(target) then
            output = output .. line .. "\n"
        end
    end
    -- 移除末尾多余的换行符
    return output:sub(1, -2) or ""
end

-- 测试示例
local str = [[hello1 : hello01
hello2 : hello02
hello3 : hello03]]

print(grep(str, "hello2"))

执行后输出:

hello2 : hello02

如果需要支持正则表达式匹配,直接把target换成正则模式即可,比如匹配以hello2开头的行,传入^hello2作为参数。

方案二:利用string.gsub批量替换

通过正则匹配保留符合条件的行,过滤掉不符合的行:

local str = [[hello1 : hello01
hello2 : hello02
hello3 : hello03]]

-- 保留包含"hello2"的行,同时处理首尾多余内容
local result = str:gsub("[^\r\n]*hello2[^\r\n]*[\r\n]?", "%0"):gsub("^[^\r\n]+[\r\n]?", ""):gsub("[\r\n]+[^\r\n]+$", "")
print(result)

这种方式适合单行代码实现,但可读性不如方案一。

补充说明

string.find只能返回匹配文本的起始/结束索引,无法直接提取整行,因此需要结合行分割逻辑来完成类似grep的功能。

内容的提问来源于stack exchange,提问作者user123454321

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 08:15:52