9

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?

Yu Hao
  • 111,229
  • 40
  • 211
  • 267
mos
  • 225
  • 2
  • 7

2 Answers2

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'(.*/)(.*)'
Yu Hao
  • 111,229
  • 40
  • 211
  • 267
3

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

pos = #s - s:reverse():find("/") + 1
catwell
  • 6,067
  • 20
  • 19