如何在Lua中实现string.rfind

mos*_*mos 9 string lua lua-patterns

在Lua只有string.find,但有时string.rfind需要.例如,要解析目录和文件路径,例如:

fullpath = "c:/abc/def/test.lua"
pos = string.rfind(fullpath,'/')
dir = string.sub(fullpath,pos)
Run Code Online (Sandbox Code Playgroud)

怎么写这样的string.rfind

Yu *_*Hao 6

你可以使用string.match:

fullpath = "c:/abc/def/test.lua"
dir = string.match(fullpath, ".*/")
file = string.match(fullpath, ".*/(.*)")
Run Code Online (Sandbox Code Playgroud)

在模式中,这.*是贪婪的,因此它在匹配之前将尽可能多地匹配/

更新:

正如@Egor Skriptunoff指出的那样,这更好:

dir, file = fullpath:match'(.*/)(.*)'
Run Code Online (Sandbox Code Playgroud)