Lua remove first directory from path

How can I remove the first directory from path string (if exists)?

I tried several times with gsub and string.match but I cannot get this working.

Inputs:

/
/tmp/file.txt
/tmp/folder/file2.txt
/tmp/folder/.../file3.txt

Outputs:

/
/file.txt
/folder/file2.txt
/folder/.../file3.txt

1 answer

  • answered 2020-10-16 04:43 Alexander Mashin

    local paths = {
        '/',
        '/tmp/file.txt',
        '/tmp/folder/file2.txt',
        '/tmp/folder/.../file3.txt'
    }
    
    for _, path in ipairs (paths) do
        local trimmed = path:gsub ('^/[^/]+', '')
        print (trimmed)
    end
    

    The necessary regular expression is ^/[^/]+. It is anchored to the beginning of the string and requires at least one non-slash character after, so that / does not match.