How to implement string.rfind in Lua
Asked Answered
P

2

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?

Pomegranate answered 30/6, 2013 at 3:16 Comment(0)
J
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'(.*/)(.*)'
Jorge answered 30/6, 2013 at 4:13 Comment(1)
dir, file = fullpath:match'(.*/)(.*)'Hedberg
M
4

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

pos = #s - s:reverse():find("/") + 1
Marlo answered 1/7, 2013 at 13:47 Comment(2)
This gives the same result: pos = s:match'.*()/'Hedberg
Do notice that in general reversing the string also reverses the substring you're looking for.Cornelia

© 2022 - 2024 — McMap. All rights reserved.