Pergunta

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?

Foi útil?

Solução

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'(.*/)(.*)'

Outras dicas

Yu & Egor's answer works. Another possibility using find would be to reverse the string:

pos = #s - s:reverse():find("/") + 1
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top