-1

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

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Ali Awan
  • 180
  • 10

1 Answers1

0

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.

Luatic
  • 8,513
  • 2
  • 13
  • 34
  • Thanks this works! I would appreciate it if you could explain how the regular expression works. – Ali Awan May 18 '22 at 19:50
  • @AliAwan first it greedily matches everything up to the backslash preceding the parent dir. Then follows the backslash. After that it lazily matches the parent dir, followed by another backslash and finally the filename; the filename and the path leading to the parent dir are captured. Note that the first quantifier is greedy, matching an arbitrarily long path, whereas the former two quantifiers are lazy, matching only the name of the parent dir and the file. `^` and `$` are simply used to anchor the pattern, forcing it to match the entire path. – Luatic May 18 '22 at 19:53