Lua 移除路径中的第一个目录

如何从路径字符串中移除第一个目录(如果存在)?

我已经尝试了多次使用 gsubstring.match 但是无法让它工作。

输入:

/
/tmp/file.txt
/tmp/folder/file2.txt
/tmp/folder/.../file3.txt

输出:

/
/file.txt
/folder/file2.txt
/folder/.../file3.txt
点赞
用户6632736
用户6632736
local paths = {
    '/',
    '/tmp/file.txt',
    '/tmp/folder/file2.txt',
    '/tmp/folder/.../file3.txt'
}

-- 循环遍历路径数组
for _, path in ipairs (paths) do
    local trimmed = path:gsub ('^/[^/]+', '') -- 使用正则表达式去掉开头所有非斜杠字符
    print (trimmed) -- 输出去掉开头所有非斜杠字符后的字符串
end

需要使用的正则表达式是 ^/[^/]+。它锚定在字符串的开头,并需要至少一个非斜杠字符,以防止斜杠 / 匹配。

2020-10-16 04:43:41
用户3342050
用户3342050
#! /usr/bin/env lua

dirsep = package.config:sub(1, 1)
cwd = '/tmp/folder/file2.txt'
delimeter = {cwd:find(dirsep, 2)}
subdir = cwd:sub(delimeter[1] or 1)

print(subdir)

输出:

/folder/file2.txt
2020-10-21 08:00:53