Lua 从请求 uri 中删除文件路径中的文件夹

Lua remove folders in file path from request uri

我有 URL 是这样的:

/path1/path2/path3/path4/path5/96_6.txt
/path1/path2/path3/path4/path5/96_7.txt?blah=1

到目前为止,我正在执行以下操作以获取 URL 末尾的文件:

local request_uri = "/path1/path2/path3/path4/path5/96_645.txt?lol=1"
local name = request_uri:match( "([^/]+)$" )
local filename = string.gsub(name, "?.*", "")


print(name)
print(filename)

什么输出:

96_645.txt?lol=1
96_645.txt

我想要做的是从我的 URL 中删除 path2path3。问题是它们是动态文件夹路径并且可以包含字符。

最好的解决方案是什么?

试试这个:

function fix_url(p)
  p, _ = string.gsub(p, '^/([^/]+)/[^/]+/[^/]+/(.*)', '/%1/%2')
  return p
end

这里有一些测试:

p = fix_url('/path1/path2/path3/path4/path5/96_6.txt') 
assert(p == '/path1/path4/path5/96_6.txt')
p = fix_url('/path1/path2/path3/path4/path5/96_7.txt?blah=1') 
assert(p == '/path1/path4/path5/96_7.txt?blah=1')
p = fix_url('/path1/foo.txt') 
assert(p == '/path1/foo.txt')