I have URL's like this:
/path1/path2/path3/path4/path5/96_6.txt
/path1/path2/path3/path4/path5/96_7.txt?blah=1
So far I am doing the following to obtain the file on the end of my 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)
What outputs:
96_645.txt?lol=1
96_645.txt
What I want to do is to remove path2
and path3
from my URL. The issue is they are dynamic folder paths and can contain characters.
What is the best solution for this?
Try this one:
function fix_url(p)
p, _ = string.gsub(p, '^/([^/]+)/[^/]+/[^/]+/(.*)', '/%1/%2')
return p
end
Here are some tests:
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')