I'm trying to use a regular expression in Lua to check if a file path ends with specific extensions
(e.g., .mp4, .mkv, .avi, .mov, .flv, .wmv).
I want to avoid using a for loop to check each extension individually and instead use a single regex pattern.
local myFile = "/test/file.mp4"
if myFile:lower():match("%.(mp4|mkv|avi|mov|flv|wmv)$") then
print("match")
end
I expect the code to print match
when myFile ends with .mp4
, .mkv
, .avi
, .mov
, .flv
, or .wmv
.
For example, /test/file.mp4
should print match
.
The code does not print match
Lua doesn't support regular expression, this is called pattern in lua, you should use the vim.regex
API instead.
local myFile = "/test/file.mp4"
-- local regex = vim.regex('\\c\\.\\(mp4\\|mkv\\|avi\\|mov\\|flv\\|wmv\\)$')
local regex = vim.regex([[\c\.\(mp4\|mkv\|avi\|mov\|flv\|wmv\)$]]) -- same as above
if regex:match_str(myFile) then
print("match")
end
The \\c
flag in the pattern is used to ignore case.