'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.

lua


Solution 1:[1]

(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)

Solution 2:[2]

Try url:match("//.-/.+(%..*)$")).

The pattern finds the first / after //, thus skipping the host part. Then it finds the last . and captures it together with the extension, if any.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 darkfrei
Solution 2 lhf