在 Lua 中只有string.find
,但有时string.rfind
需要。例如,解析目录和文件路径,如:
fullpath = "c:/abc/def/test.lua"
pos = string.rfind(fullpath,'/')
dir = string.sub(fullpath,pos)
怎么写这样的string.rfind
?
在 Lua 中只有string.find
,但有时string.rfind
需要。例如,解析目录和文件路径,如:
fullpath = "c:/abc/def/test.lua"
pos = string.rfind(fullpath,'/')
dir = string.sub(fullpath,pos)
怎么写这样的string.rfind
?
You can use string.match
:
fullpath = "c:/abc/def/test.lua"
dir = string.match(fullpath, ".*/")
file = string.match(fullpath, ".*/(.*)")
Here in the pattern, .*
is greedy, so that it will match as much as it can before it matches /
UPDATE:
As @Egor Skriptunoff points out, this is better:
dir, file = fullpath:match'(.*/)(.*)'
Yu & Egor 的回答很有效。使用 find 的另一种可能性是反转字符串:
pos = #s - s:reverse():find("/") + 1