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

Lua实现类其他语言的换行符字符串分割问题求助

Lua Split函数实现:保留首尾空字符串

要实现能保留首尾空字符串的split函数,核心是要完整捕获分隔符之间的所有内容——包括开头到第一个分隔符、最后一个分隔符到结尾的空串。以下是两种可靠的实现方式:

方法一:循环查找分隔符(推荐)

这种方式逻辑直观,能准确处理所有边界情况:

function split(str, sep)
    local result = {}
    local start_pos = 1
    local sep_length = #sep
    while true do
        -- 从当前位置开始查找分隔符(第三个参数true表示不使用模式匹配,按字面查找)
        local sep_pos = string.find(str, sep, start_pos, true)
        if not sep_pos then
            -- 找不到分隔符时,把剩余部分加入结果
            table.insert(result, string.sub(str, start_pos))
            break
        end
        -- 截取当前位置到分隔符前的部分(可能是空串)
        table.insert(result, string.sub(str, start_pos, sep_pos - 1))
        -- 更新起始位置到分隔符之后
        start_pos = sep_pos + sep_length
    end
    return result
end

方法二:结合gmatch与收尾处理

如果习惯用gmatch,需要额外处理最后一个分隔符后的内容:

function split(str, sep)
    local result = {}
    -- 匹配每个分隔符前的部分
    for part in string.gmatch(str, "(.-)" .. sep) do
        table.insert(result, part)
    end
    -- 提取最后一个分隔符之后的内容(包括空串)
    local last_sep_pos = string.find(str, sep .. "$")
    local last_part = last_sep_pos and string.sub(str, last_sep_pos + #sep) or str
    table.insert(result, last_part)
    return result
end

测试验证

用你的测试字符串验证:

local test_str = '\nhello\nworld\n'
local parts = split(test_str, '\n')

-- 输出结果:
-- 1   ""
-- 2   "hello"
-- 3   "world"
-- 4   ""
for idx, val in ipairs(parts) do
    print(idx, val == "" and '""' or val)
end

两种方法都能得到你期望的{ "", "hello", "world", "" }数组,完美处理首尾空串的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:45:48