如何在Lua中实现string.rfind

如何在Lua中实现string.rfind,string,lua,lua-patterns,String,Lua,Lua Patterns,在Lua中只有string.find,但有时需要string.rfind。例如,要解析目录和文件路径,请执行以下操作: fullpath = "c:/abc/def/test.lua" pos = string.rfind(fullpath,'/') dir = string.sub(fullpath,pos) 如何编写这样的string.rfind?您可以使用string.match: fullpath = "c:/abc/def/test.lua" dir = string.match(f

在Lua中只有
string.find
,但有时需要
string.rfind
。例如,要解析目录和文件路径,请执行以下操作:

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

如何编写这样的
string.rfind

您可以使用
string.match

fullpath = "c:/abc/def/test.lua"
dir = string.match(fullpath, ".*/")
file = string.match(fullpath, ".*/(.*)")
在模式中,
*
是贪婪的,因此在匹配
/
之前,它将尽可能多地匹配

更新

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

dir, file = fullpath:match'(.*/)(.*)'

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

pos = #s - s:reverse():find("/") + 1

dir,file=fullpath:match'(.*/)(.*)这是一个好主意,谢谢。这会给出相同的结果:
pos=s:match'.*()/”
注意,通常反转字符串也会反转您要查找的子字符串。