来自对deepseek的询问
要能够处理/a/b/s a/b/s /a/b/s/这些情况,并且把分割的单独的储存在一个容器里面
在 Lua 中,你可以编写一个 通用的路径分割函数,它能处理以下各种情况:
/a/b/s/(前后有斜杠)a/b/s(前后无斜杠)/a/b/s(仅前面有斜杠)a/b/s/(仅后面有斜杠)
并返回一个 数组(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}
解析
string.gmatch(path, "([^/]+)")会匹配所有 非/的连续字符。if part ~= ""过滤掉可能因多个/导致的空匹配(如///a//b//s///)。- 最终返回一个数组
parts,包含{"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解析
trim_slashes使用string.gsub去除首尾/:^/*匹配 开头 0 或多个/。(.-)匹配 中间任意字符(非贪婪)。/*$匹配 结尾 0 或多个/。"%1"保留 中间部分(a/b/s)。
- 然后再用
string.gmatch分割。
总结
| 方法 | 适用场景 | 特点 |
|---|---|---|
string.gmatch + 过滤空串 |
通用情况(推荐) | 直接匹配非 / 部分,简单高效 |
先 trim 再分割 |
需要严格去除首尾 / |
更可控,但多一步处理 |
推荐使用方法 1,因为它:
- 代码更简洁,直接过滤空字符串。
- 能处理各种情况,包括
///a//b//s///这种极端情况。 - 返回数组,方便后续操作(如
parts[1]是"a")。
你可以直接调用 split_path(path),它会返回 {"a", "b", "s"},适用于所有情况! 🚀