9

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

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

怎么写这样的string.rfind

4

2 回答 2

8

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'(.*/)(.*)'
于 2013-06-30T04:13:03.240 回答
4

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

pos = #s - s:reverse():find("/") + 1
于 2013-07-01T13:47:25.837 回答