23

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.

Paul Kulchenko
  • 25,884
  • 3
  • 38
  • 56
Jane T
  • 2,081
  • 2
  • 17
  • 23
  • 1
    I'd argue just reading the string backwards is a better way to do it - pattern matching is overkill in this situation, will probably run 10x times slower and will take longer to grasp once you are in a maintenance state and have forgotten every detail of your code. – sbk Mar 09 '11 at 16:52

3 Answers3

39

Here is an improved version that works for Windows and Unix paths and also handles files without dots (or files with multiple dots):

= string.match([[/mnt/tmp/myfile.txt]], "(.-)([^\\/]-%.?([^%.\\/]*))$")
"/mnt/tmp/" "myfile.txt"    "txt"

= string.match([[/mnt/tmp/myfile.txt.1]], "(.-)([^\\/]-%.?([^%.\\/]*))$")
"/mnt/tmp/" "myfile.txt.1"  "1"

= string.match([[c:\temp\test\myfile.txt]], "(.-)([^\\/]-%.?([^%.\\/]*))$")
"c:\\temp\\test\\"  "myfile.txt"    "txt"

= string.match([[/test.i/directory.here/filename]], "(.-)([^\\/]-%.?([^%.\\/]*))$")
"/test.i/directory.here/"   "filename"  "filename"
Paul Kulchenko
  • 25,884
  • 3
  • 38
  • 56
19
> return string.match([[c:\temp\test\myfile.txt]], "(.-)([^\\]-([^%.]+))$")
c:\temp\test\   myfile.txt  txt

This seems to do exactly what you want.

Arrowmaster
  • 9,143
  • 2
  • 28
  • 25
  • Thank you so much, you don't want to know how long I played with the match string, I will work through your answer to learn how it works. – Jane T Mar 09 '11 at 09:33
  • 1
    @Jane: the important things to note are the non-greedy `-`'s and their placement. – Arrowmaster Mar 09 '11 at 09:39
0

Split string in Lua?

There is a few string to table functions there, split "\" as \ cant be in a folder name anyway so you'll end up with a table with index one being the drive and the last index being the file.

Community
  • 1
  • 1
Col_Blimp
  • 779
  • 2
  • 8
  • 26