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

Lua中如何分割字符串并保留空格?统计开头空格数方法

解决Lua中字符串缩进统计与带空格分割的问题

一、统计字符串开头的空格数量

直接利用Lua的字符串匹配功能就能快速实现,通过匹配开头连续的空格字符,再获取其长度即可。示例代码如下:

function countLeadingSpaces(str)
    -- ^%s* 匹配开头所有空白字符,若只想统计空格,把%s换成空格即可
    local spaces = str:match("^%s*")
    return #spaces, str:sub(#spaces + 1)
end

-- 测试用例
local testStrings = {" item", "   item", "no space item", "  item  with trailing"}
for _, s in ipairs(testStrings) do
    local spaceCount, content = countLeadingSpaces(s)
    print("空格数: " .. spaceCount .. ", 内容: '" .. content .. "'")
end

这段代码会返回字符串开头的空格数量,以及去掉开头空格后的纯内容,刚好满足你渲染时获取缩进量和条目内容的需求。

二、Lua中分割字符串并保留空格的方案

Lua标准库没有内置split函数,需要自行实现,以下是两种适配不同场景的方案:

1. 按指定分隔符分割,保留所有原始空格

如果需要按特定分隔符(比如逗号、分号)分割字符串,同时保留每个分割部分的前后空格,可以用这个实现:

function splitWithSpaces(str, sep)
    sep = sep or ","  -- 默认按逗号分割,可自行指定
    local parts = {}
    -- 匹配分隔符前的所有内容(包括空格)
    local pattern = "([^" .. sep .. "]*)" .. sep
    for part in str:gmatch(pattern) do
        table.insert(parts, part)
    end
    -- 处理最后一个分隔符后的剩余内容
    local lastPart = str:match("([^" .. sep .. "]*)$")
    if lastPart then
        table.insert(parts, lastPart)
    end
    return parts
end

-- 测试用例
local testStr = "  apple, banana  ,  cherry"
local result = splitWithSpaces(testStr, ",")
for i, part in ipairs(result) do
    print("部分" .. i .. ": '" .. part .. "'")
end

运行后会得到保留所有原始空格的分割结果,比如第一个部分是" apple",第二个是" banana "。

2. 拆分缩进与内容的结构化处理(适配渲染需求)

如果你的核心需求是为了渲染带缩进的条目,可以直接结合第一个统计空格的函数,把每个字符串拆分成缩进量和内容的结构:

local items = {" item", "   item", "  sub item"}
local processedItems = {}
for _, s in ipairs(items) do
    local spaceCount, content = countLeadingSpaces(s)
    table.insert(processedItems, {indent = spaceCount, text = content})
end

-- 渲染示例:按每个原始空格对应2个渲染空格的规则输出
for _, item in ipairs(processedItems) do
    local indentStr = string.rep(" ", item.indent * 2)
    print(indentStr .. item.text)
end

这种方式把缩进信息和内容分离,方便后续根据需求调整渲染的缩进级别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 06:42:43