如何在Lua中实现string.rfind函数

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

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

如何编写这样的 string.rfind

点赞
用户1009479
用户1009479

你可以使用 string.match

fullpath = "c:/abc/def/test.lua"
dir = string.match(fullpath, ".*/")
file = string.match(fullpath, ".*/(.*)")

在这个模式中,. * 是贪婪的,因此它将匹配尽可能多的内容,直到它匹配到 /

更新

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

dir, file = fullpath:match'(.*/)(.*)'
2013-06-30 04:13:03
用户204011
用户204011

Yu & Egor的答案可行。另一种使用find的可能性是反转字符串:

pos = #s - s:reverse():find("/") + 1
2013-07-01 13:47:25