LUA字符串路径中获取文件名、路径的模式匹配

时间:2022-06-01 20:29:05
--获取路径
function stripfilename(filename)
return string.match(filename, "(.+)/[^/]*%.%w+$") --*nix system
--return string.match(filename, “(.+)\\[^\\]*%.%w+$”) — windows
end

--获取文件名
function strippath(filename)
return string.match(filename, ".+/([^/]*%.%w+)$") -- *nix system
--return string.match(filename, “.+\\([^\\]*%.%w+)$”) — *nix system
end

--去除扩展名
function stripextension(filename)
local idx = filename:match(".+()%.%w+$")
if(idx) then
return filename:sub(1, idx-1)
else
return filename
end
end

--获取扩展名
function getextension(filename)
return filename:match(".+%.(%w+)$")
end

local paths = "/use/local/openresty/nginx/movies/fffff.tar.gz"
print (stripfilename(paths))
print (strippath(paths))
print (stripextension(paths))
print (getextension(paths))


[root@localhost cdnlua]# lua testfile.lua 


/use/local/openresty/nginx/movies
fffff.tar.gz
/use/local/openresty/nginx/movies/fffff.tar
gz