Search code examples
stringluapathfilenameslua-patterns

Remove both path and extension from string in Lua


I'm trying to get the name of the file without the path and the extension in one go. I am using string.match and ([^\\/]+)$ to get rid of the path and then another string.match with (.+)%.[^.]+$ to get rid of the extension. This works but I was wondering if there's a way to get rid of both of them using string.match only once. Any way to combine the two regex codes?

I've tried various other regex codes on the internet but it seems that Lua doesn't play well with all of them.

In practice:

entirepath = "C:/Users/mail/Desktop/Something/Test.mp3"

justname = string.match(entirepath, "code that keeps only filename")

print(justname)

Result should be Test.


Solution

  • You can try this:

    local path = "/path/to/your/file/filename.txt"
    local filename, extension = path:match("^.+/(.+)%.(.+)$")
    
    print("Filename: " .. filename)
    print("Extension: " .. extension)