user177800
user177800

Reputation:

Last Index of Character in String

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?

Upvotes: 20

Views: 18916

Answers (5)

MaDDoX
MaDDoX

Reputation: 598

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.

Upvotes: 4

Rafał Rychlewski
Rafał Rychlewski

Reputation: 99

Here is a complete solution.

local function basename(path)
  return path:sub(path:find("/[^/]*$") + 1)
end

Upvotes: 2

Amber
Amber

Reputation: 527448

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.)

Upvotes: 27

summer
summer

Reputation: 47

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

Upvotes: 1

Egor Skriptunoff
Egor Skriptunoff

Reputation: 23767

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

index = your_string:match'^.*()/'

Upvotes: 7

Related Questions