19

How do you get the last index of a character in a string in Lua?

"/some/path/to/some/file.txt"

How do I get the index of the last / in the above string?

5 Answers5

24
index = string.find(your_string, "/[^/]*$")

(Basically, find the position where the pattern "a forward slash, then zero or more things that aren't a forward slash, then the end of the string" occurs.)

Amber
  • 507,862
  • 82
  • 626
  • 550
7

This method is a bit more faster (it searches from the end of the string):

index = your_string:match'^.*()/'
Egor Skriptunoff
  • 23,359
  • 2
  • 34
  • 64
4

Loops?!? Why would you need a loop for that? There's a 'reverse' native string function mind you, just apply it then get the first instance :) Follows a sample, to get the extension from a complete path:

function fileExtension(path)
    local lastdotpos = (path:reverse()):find("%.")
    return (path:sub(1 - lastdotpos))
end

You can do it in a single line of course, I split it in two for legibility's sake.

Termininja
  • 6,620
  • 12
  • 48
  • 49
MaDDoX
  • 598
  • 5
  • 8
2

Here is a complete solution.

local function basename(path)
  return path:sub(path:find("/[^/]*$") + 1)
end
aleclarson
  • 18,087
  • 14
  • 64
  • 91
1
local s = "/aa/bb/cc/dd/ee.txt"
local sep = "/"

local lastIndex = nil
local p = string.find(s, sep, 1)
lastIndex = p
while p do
    p = string.find(s, sep, p + 1)
    if p then
        lastIndex = p
    end
end
print(lastIndex)

You could continue find next value, until find nil,record last position

summer
  • 47
  • 4