What is the neatest way to split out a Path Name into its components in Lua
Solution 1
> return string.match([[c:\temp\test\myfile.txt]], "(.-)([^\\]-([^%.]+))$")
c:\temp\test\ myfile.txt txt
This seems to do exactly what you want.
Solution 2
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"
Related videos on Youtube
Jane T
Long time programmer, using a variety of Languages, currently learning Lua for a new Project. Programming languages can be learnt by heart but mastered by practice. -Majid-
Updated on March 17, 2020Comments
-
Jane T about 4 years
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.
-
Jane T about 13 yearsThank 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.
-
Arrowmaster about 13 years@Jane: the important things to note are the non-greedy
-
's and their placement.