rootprefix

function rootprefix( path ) --> prefix

Description

Returns the root element from a path, if exiting.

Parameters

path

The path to query.

Return Values

prefix

The root element in the path.

Code

--ZFUNC-rootprefix-v1
local function rootprefix( path ) --> prefix
   local remote = path:match[[^//%w+/]] or path:match[[^\\%w+\]]
   if remote then return remote end

   local unix = path:sub( 1, 1 )
   if unix == "/" then return unix end

   local win = path:match[=[^[a-zA-Z]:[\\/]]=]
   if win then return win end

   return ""
end

return rootprefix

Examples

local t = require( "taptest" )
local rootprefix = require( "rootprefix" )

-- win paths
t( rootprefix[[a\b\c.txt]], "" )
t( rootprefix[[C:a\b\c.txt]], "" )
t( rootprefix[[C:\a\b\c.txt]], "C:\\" )
t( rootprefix( "C:/a/b/c.txt" ), "C:/" )
t( rootprefix[[\\server\a\b\c.txt]], [[\\server\]] )

-- unix paths
t( rootprefix( "a/b/c,txt" ), "" )
t( rootprefix( "~/a/b/c.txt" ), "" )
t( rootprefix( "/a/b/c.txt" ), "/" )

t()