How do you find the last occurrence of the template using string.find?

I was trying to find out if I can find the last occurrence of the pattern instead of the first using string.fing Eg: in the string "AAAAABBB" I want to find the position of the last "A" isntead of the first.

Is it possible?

thank

+3


source to share


2 answers


Try using an empty capture:

str = "123456AAA7890AAABBBB"
print(str:match(".*()A"))

      



If you need to use string.find

, try this:

local _,p = str:find(".*A")
print(p)

      

+3


source


local str = "123456AAA7890AAABBBB"
local s, e = str:find("A[^A]*$")

print(s)
print(str:sub(s))

      

Alternatively reverse the line and use a simpler call string.find

.



local str = "123456AAA7890AAABBBB"
local revstr = str:reverse()
local ind = revstr:find("A")

print(#revstr - ind + 1)
print(str:sub(#revstr - ind + 1))

      

+3


source







All Articles