Search code examples
lua

lua get file extension first occurrence


So i have a url like so

https://example.com/path/to/file/file.mp4/file.jpg

I want to match only the first provided file extension provided not any others people insert into the url.

Example :

function GetFileExtension(url)
return url:match("^.+(%..+)$")
end

local url = "https://example.com/path/to/file/file.mp4/file.jpg"
print(GetFileExtension(url))

Output :

.jpg

The output should be a .mp4 since that is what the file is anything after the first occurrence is ignored on the url.

What is the best way to fix this. Thanks to anyone who can help me and answer my question.


Solution

  • (Thanks to Josh)

    filename = "https://example.com/path/to/file/file.mp4/file.jpg"
    --ext = filename:match("^.+(%..+)$")  -- ".jpg"
    --ext = filename:match("^.+%.(.+)$")  -- "jpg"
    --ext = filename:match("^.+(%..+)%/") -- ".mp4"
      ext = filename:match("^.+%.(.+)%/") -- "mp4"
    
    print (ext)