Page 1 of 1

Handling filenames without extensions

Posted: 11 Oct 2018 14:34
by ColeValleyGirl
I'm writing a plugin that needs (among other things) to split a file name into path, filename and extension.

I'm trying to use the following code snippet:

Code: Select all

    function SplitFilename(strFilename)
    	-- Returns the Path, Filename, and Extension as 3 values
    	if lfs.attributes(strFilename,"mode") == "directory" then
    		local strPath = strFilename:gsub("[\\/]$","")
    		return strPath.."\\","",""
    	end
    	return strFilename:match("(.-)([^\\/]-([^\\/%.]+))$")
    end

but am finding it fails when the file does not have an extension.

For example, fed "C://example.com/path/image_without_extension"

it returns

Code: Select all

C://example.com/path/
image_without_extension
image_without_extension
whereas "C://example.com/path/image_without_extension.tif"

returns

Code: Select all

C://example.com/path/
image_without_extension.tif
tif
Ideally I want the function to return:

the complete path
the filename without trailing . or extension
the extension

so e.g.

Code: Select all

C://example.com/path/
image_without_extension
tif
or

Code: Select all

C://example.com/path/
image_without_extension
nil


Anyone suggest how I can modify it -- or point me to a utility for creating Lua patterns (I have one for all flavours of regex, but can't find one for patterns)

Re: Handling filenames without extensions

Posted: 11 Oct 2018 15:15
by tatewise
plugins:code_snippets:split_filename_in_to_path_filename_and_extension|> Split a Filename into Path, File, and Extension (code snippet).

Yes, it is a bit tricky, but the following works:

strFilename = strFilename.."."
return strFilename:match("^(.-)([^\\/]-)%.([^\\/%.]-)%.?$")

All the following are correctly parsed:
local p,f,e = Filename("C:\\User\\name")
local p,f,e = Filename("C:\\User\\name.")
local p,f,e = Filename("C:\\User\\name.tif")
local p,f,e = Filename("C:\\User\\name.one.tif")
local p,f,e = Filename("C:\\User.X\\name.one.tif")
It is these last two cases that needs the dot appended to strFilename to cope with a dot within the filename part.

I will add that refinement to the Code Snippet.

I am not aware of a utility for creating Lua Patterns.

Re: Handling filenames without extensions

Posted: 11 Oct 2018 15:29
by ColeValleyGirl
Thanks, Mike -- I've been scratching my head over if for a day. Now on to the next thing in the plugin snagging list...