【问题标题】:Finding all instances of a string within a string在字符串中查找字符串的所有实例
【发布时间】:2020-02-17 21:52:33
【问题描述】:

有什么方法可以在 lua 中找到(并循环遍历)另一个字符串中的一个字符串的所有实例?例如,如果我有字符串

"honewaidoneaeifjoneaowieone"

我想遍历该字符串中“one”的所有实例(我指的是索引),好吧,我可以看到它出现了四次,但我不知道如何实际找到它们。我知道 string.find() 可以找到第一个实例,但这对我帮助不大。

【问题讨论】:

  • for index in ("honewaidoneaeifjoneaowieone"):gmatch("()one") do print(index) end
  • 看起来它会起作用。您可以将其发布为答案吗?
  • 如果您在字符串 aaaa 中搜索子字符串 aaa,我的解决方案将无法正常工作。让我们等待“find()-inside-a-loop”解决方案的答案。
  • 好的。它对我有用,因为我的案例适用于此,但“()one”中的括号有什么作用?
  • 空括号表示“位置索引”

标签: string loops lua find


【解决方案1】:
local str = "honewaidoneaeifjoneaowieone"

-- This one only gives you the substring;
-- it doesn't tell you where it starts or ends
for substring in str:gmatch 'one' do
   print(substring)
end

-- This loop tells you where the substrings
-- start and end. You can use these values in
-- string.find to get the matched string.
local first, last = 0
while true do
   first, last = str:find("one", first+1)
   if not first then break end
   print(str:sub(first, last), first, last)
end

-- Same as above, but as a recursive function
-- that takes a callback and calls it on the
-- result so it can be reused more easily
local function find(str, substr, callback, init)
   init = init or 1
   local first, last = str:find(substr, init)
   if first then
       callback(str, first, last)
       return find(str, substr, callback, last+1)
   end
end

find(str, 'one', print)

【讨论】:

    【解决方案2】:

    你可以告诉string.find从哪里开始搜索:

    s="honewaidoneaeifjoneaowieone"
    p="one"
    b=1
    while true do
        local x,y=string.find(s,p,b,true)
        if x==nil then break end
        print(x)
        b=y+1
    end
    

    此代码在前一个匹配结束后开始每次搜索,也就是说,它只查找不重叠的字符串。如果您想查找重复出现的字符串,请改用b=x+1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      • 2010-10-25
      • 1970-01-01
      • 2021-12-18
      • 2011-03-22
      • 2012-11-03
      相关资源
      最近更新 更多