Search code examples
lualua-patterns

What is the neatest way to split out a Path Name into its components in Lua


I have a standard Windows Filename with Path. I need to split out the filename, extension and path from the string.

I am currently simply reading the string backwards from the end looking for . to cut off the extension, and the first \ to get the path.

I am sure I should be able to do this using a Lua pattern, but I keep failing when it comes to working from the right of the string.

eg. c:\temp\test\myfile.txt should return

  • c:\temp\test\
  • myfile.txt
  • txt

Thank you in advance apologies if this is a duplicate, but I could find lots of examples for other languages, but not for Lua.


Solution

  • > return string.match([[c:\temp\test\myfile.txt]], "(.-)([^\\]-([^%.]+))$")
    c:\temp\test\   myfile.txt  txt
    

    This seems to do exactly what you want.