我希望能够在我的Lua(Luvit)项目中使用字符串的lastIndexOf
方法。不幸的是,这种方法没有内置在Lua中,我现在有点困难。
在Javascript中它看起来像:
'my.string.here.'.lastIndexOf('.') // returns 14
function findLast(haystack, needle)
local i=haystack:match(".*"..needle.."()")
if i==nil then return nil else return i-1 end
end
s='my.string.here.'
print(findLast(s,"%."))
print(findLast(s,"e"))
请注意,要查找 .
,您需要对其进行转义。
local find = string.find
local function lastIndexOf(haystack, needle)
local i, j
local k = 0
repeat
i = j
j, k = find(haystack, needle, k + 1, true)
until j == nil
return i
end
local s = 'my.string.here.'
print(lastIndexOf(s, '.')) -- This will be 15.
请记住,Lua字符串从1
开始,而不是像JavaScript一样从0
开始。
lastIndexOfFind
非常接近。唯一的区别是我的函数返回 nil
而不是 -1
,这更符合 Lua 的风格。哦,我的函数从 string.find
的第二个返回值开始,这意味着它跳过了一些不必要 - Ryan Stein要在haystack
中查找字符串needle
的最后一个实例:
function findLast(haystack, needle)
--Set the third arg to false to allow pattern matching
local found = haystack:reverse():find(needle:reverse(), nil, true)
if found then
return haystack:len() - needle:len() - found + 2
else
return found
end
end
print(findLast("my.string.here.", ".")) -- 15, because Lua strings are 1-indexed
print(findLast("my.string.here.", "here")) -- 11
print(findLast("my.string.here.", "there")) -- nil
如果你想要查找模式的最后一个实例,只需将最后一个参数更改为false
(或删除它)。
1
。 - Ryan Steinlocal lpeg = require "lpeg"
local Cp, P = lpeg.Cp, lpeg.P
local lpegmatch = lpeg.match
local cache = { }
local find_last = function (str, substr)
if not (str and substr)
or str == "" or substr == ""
then
return nil
end
local pat = cache [substr]
if not pat then
local p_substr = P (substr)
local last = Cp() * p_substr * Cp() * (1 - p_substr)^0 * -1
pat = (1 - last)^0 * last
cache [substr] = pat
end
return lpegmatch (pat, str)
end
find_last()
函数用于在字符串str中查找substr最后一次出现的位置,substr可以是任意长度的字符串。第一个返回值是substr在str中第一个字符的位置,第二个返回值是substr匹配的长度加上第一个返回值后的第一个字符的位置。使用方法:
local tests = {
A = [[fooA]], --> 4, 5
[""] = [[foo]], --> nil
FOO = [[]], --> nil
K = [[foo]], --> nil
X = [[X foo X bar X baz]], --> 13, 14
XX = [[foo XX X XY bar XX baz X]], --> 17, 19
Y = [[YYYYYYYYYYYYYYYYYY]], --> 18, 19
ZZZ = [[ZZZZZZZZZZZZZZZZZZ]], --> 14, 17
--- Accepts patterns as well!
[P"X" * lpeg.R"09"^1] = [[fooX42barXxbazX]], --> 4, 7
}
for substr, str in next, tests do
print (">>", substr, str, "->", find_last (str, substr))
end
可以进行优化,但简单且能够完成工作。
function lastIndexOf(haystack, needle)
local last_index = 0
while haystack:sub(last_index+1, haystack:len()):find(needle) ~= nil do
last_index = last_index + haystack:sub(last_index+1, haystack:len()):find(needle)
end
return last_index
end
local s = 'my.string.here.'
print(lastIndexOf(s, '%.')) -- 15
string.find
('my.string.here.'):find("%.[^.]-$")
。但你需要转义特殊字符(例如.
,*
,+
等)。在 Lua 中,结果应该是 15。 - moteus