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

9
在 Lua 中只有 string.find, 但有时需要使用 string.rfind。例如,解析目录和文件路径:
fullpath = "c:/abc/def/test.lua"
pos = string.rfind(fullpath,'/')
dir = string.sub(fullpath,pos)

如何编写类似于string.rfind的函数?
2个回答

8
您可以使用 string.match
fullpath = "c:/abc/def/test.lua"
dir = string.match(fullpath, ".*/")
file = string.match(fullpath, ".*/(.*)")

在这个模式中,.*是贪婪的,因此在匹配/之前它将尽可能多地匹配。 更新: 正如@Egor Skriptunoff指出的那样,以下方式更好:
dir, file = fullpath:match'(.*/)(.*)'

1
dir, file = fullpath:match'(./)(.)' 目录,文件=fullpath:match'(./)(.)' - Egor Skriptunoff

4

Yu和Egor的答案是正确的。使用find的另一个可能性是反转字符串:

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

这将得到相同的结果:pos = s:match'.*()/' - Egor Skriptunoff
2
请注意,通常反转字符串也会反转您正在查找的子字符串。 - James Koss

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接