Home > other >  lua help to get an end of string after last special character
lua help to get an end of string after last special character

Time:11-12

i have an unknow string, that contains several "/". I need all characters after the last "/". Example. (Remeber the actual string will be unknown) string= abcdefg/hijkl/123hgj-sg/diejdu/duhd3/zyxw

I need return "zyxw"

thank you all for help

im just really bad with the symbols for pattern matching and no clue how to say "return everything after the last "/""

CodePudding user response:

local function getLastFromPath(path)
    local last = path:match("([^/] )$")
    return last
end

print(getLastFromPath("abcdefg/hijkl/123hgj-sg/diejdu/duhd3/zyxw"))

Assuming you are referring to file-system paths, you can get the last bit of string by splitting every / and getting the last one in the path.

CodePudding user response:

How many ways leading to Rome?

> ustr = 'abcdefg/hijkl/123hgj-sg/diejdu/duhd3/zyxw'
> last = ustr:gsub('.*%/', '') -- I prefer gsub() method on string
> print(last)
zyxw

What to do if it is also unknown if Windows or Linux Path Convention?

> ustr = 'c:\\abcdefg\\hijkl\\123hgj-sg\\diejdu\\duhd3\\zyxw.ext'
> last = ustr:gsub('.*[%/%\\]', '') --[[ Checks for both: / and \ ]]
> print(last)
zyxw.ext
  • Related