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

3

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.

Rafael answered 9/3, 2011 at 8:41 Comment(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.Fungi
Q
19
> return string.match([[c:\temp\test\myfile.txt]], "(.-)([^\\]-([^%.]+))$")
c:\temp\test\   myfile.txt  txt

This seems to do exactly what you want.

Quarrel answered 9/3, 2011 at 9:16 Comment(2)
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.Rafael
@Jane: the important things to note are the non-greedy -'s and their placement.Quarrel
R
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"
Remand answered 30/8, 2012 at 6:40 Comment(0)
Q
19
> return string.match([[c:\temp\test\myfile.txt]], "(.-)([^\\]-([^%.]+))$")
c:\temp\test\   myfile.txt  txt

This seems to do exactly what you want.

Quarrel answered 9/3, 2011 at 9:16 Comment(2)
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.Rafael
@Jane: the important things to note are the non-greedy -'s and their placement.Quarrel
C
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.

Chameleon answered 30/8, 2012 at 1:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.