'How would I do pattern matching on this string in lua?

I have a string which contains a path to a file:

C:\Users\user\directory\build.bat

Is there a way I can remove the word between the last backslash and the second last backslash (in this case it is directory), however I would like a way to do this several times:

First time I run the code the path should look like this:

C:\Users\user\build.bat

If I run the code on the new string I just got from running the program the first time, the output should be like this:

C:\Users\build.bat



Solution 1:[1]

Yes, this is very much possible. I propose the following pattern:

^(.+)\.-\(.-)$ - this will match the entire path, matching first the directories up to the parent directory and then the filename. Use it as follows:

local function strip_parent_dir(path)
    local path_to_parent, filename = path:match[[^(.+)\.-\(.-)$]]
    return path_to_parent .. "\\" .. filename
end

which can then be used as follows:

print(strip_parent_dir[[C:\Users\user\directory\build.bat]]) -- C:\Users\user\build.bat
print(strip_parent_dir(strip_parent_dir[[C:\Users\user\directory\build.bat]])) -- C:\Users\build.bat

another option would be to split the path by the path delimiter (backslash), inserting the parts into a table, then removing the penultimate entry, finally concatenating the parts; this is slightly longer but may be considered more readable (and it may have better asymptotic performance):

local function strip_parent_dir(path)
    local parts = {}
    for part in path:gmatch"[^\\]+" do
        table.insert(parts, part)
    end
    table.remove(parts, #parts - 1)
    return table.concat(parts, "\\")
end

the results are the same. Choose whatever you consider more readable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1