lua分割路径字符串的各个单独部分

⌚Time: 2025-05-02 12:19:00

👨‍💻Author: Jack Ge

来自对deepseek的询问

要能够处理/a/b/s a/b/s /a/b/s/这些情况,并且把分割的单独的储存在一个容器里面

在 Lua 中,你可以编写一个 通用的路径分割函数,它能处理以下各种情况:

并返回一个 数组(table) 存储分割后的部分 {"a", "b", "s"}


方法 1:使用 string.gmatch + 过滤空字符串

function split_path(path)
    local parts = {}
    -- 匹配非斜杠的部分,并过滤空字符串
    for part in string.gmatch(path, "([^/]+)") do
        if part ~= "" then  -- 确保不是空字符串
            table.insert(parts, part)
        end
    end
    return parts
end

-- 测试用例
local test_paths = {
    "/a/b/s/",
    "a/b/s",
    "/a/b/s",
    "a/b/s/",
    "///a//b//s///",  -- 甚至处理多个斜杠
}

for _, path in ipairs(test_paths) do
    local parts = split_path(path)
    print(string.format("Path: '%s' -> {%s}", path, table.concat(parts, ", ")))
end

输出结果

Path: '/a/b/s/' -> {a, b, s}
Path: 'a/b/s' -> {a, b, s}
Path: '/a/b/s' -> {a, b, s}
Path: 'a/b/s/' -> {a, b, s}
Path: '///a//b//s///' -> {a, b, s}

解析


方法 2:先去除首尾 /,再分割

如果希望更严格地处理首尾 /,可以先 trim(去除首尾斜杠),再分割:

function trim_slashes(str)
    return string.gsub(str, "^/*(.-)/*$", "%1")
end

function split_path(path)
    local trimmed = trim_slashes(path)  -- 先去除首尾斜杠
    local parts = {}
    for part in string.gmatch(trimmed, "([^/]+)") do
        table.insert(parts, part)
    end
    return parts
end

-- 测试(结果同上)
local parts = split_path("///a//b//s///")
print(table.concat(parts, ", "))  -- 输出: a, b, s

解析


总结

方法 适用场景 特点
string.gmatch + 过滤空串 通用情况(推荐) 直接匹配非 / 部分,简单高效
trim 再分割 需要严格去除首尾 / 更可控,但多一步处理

推荐使用方法 1,因为它:

  1. 代码更简洁,直接过滤空字符串。
  2. 能处理各种情况,包括 ///a//b//s/// 这种极端情况。
  3. 返回数组,方便后续操作(如 parts[1]"a")。

你可以直接调用 split_path(path),它会返回 {"a", "b", "s"},适用于所有情况! 🚀