문제

In Lua there's only string.find, but sometime string.rfind is needed. For example, to parse directory and file path like:

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

How to write such 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's answer works. Another possibility using find would be to reverse the string:

pos = #s - s:reverse():find("/") + 1
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top