Lua:如何在字符串中的两个或多个重复字符之间插入内容?

这个问题在某种程度上类似于这个问题,但我的任务是在重复字符之间插入内容,例如问号,使用 gsub 函数。

示例:

"?" = "?"
"??" = "?-?"
"??? = "?-?-?"

点赞
用户107090
用户107090

尝试一下:

function test(s)
    local t=s:gsub("%?%?","?-?"):gsub("%?%?","?-?")
    print(#s,s,t)
end

for n=0,10 do
    test(string.rep("?",n))
end
函数 test(s)

    local t=s:gsub("%?%?","?-?"):gsub("%?%?","?-?")

    print(#s,s,t)

end

for n=0,10 do

    test(string.rep("?",n))

end
2020-11-26 16:56:45
用户13447666
用户13447666

将下面翻译成中文并且保留原本的 markdown 格式

这是我通过逐个扫描每个字母得出的结果

function test(str)
  local output = ""
  local tab = {}
  for let in string.gmatch(str, ".") do
    table.insert(tab, let)
  end
  local i = 1
  while i <= #tab do
    if tab[i - 1] == tab[i] then
      output = output.."-"..tab[i]
    else
      output = output..tab[i]
    end
    i = i + 1
  end
  return output
end
for n=0,10 do
  print(test(string.rep("?",n)))
end
2020-11-27 03:00:14
用户4984564
用户4984564

使用 LPeg 的可能解决方案:

local lpeg = require 'lpeg'

local head = lpeg.C(lpeg.P'?')
local tail = (lpeg.P'?' / function() return '-?' end) ^ 0

local str = lpeg.Cs((head * tail + lpeg.P(1)) ^ 1)

for n=0,10 do
    print(str:match(string.rep("?",n)))
end

print(str:match("?????foobar???foo?bar???"))

本示例使用LPeg库,该库提供了一种完整的解析表达式语言的方式。它使用head、tail函数和Cs函数,其中head和tail函数分别用于匹配字符串中的问号,Cs函数则用于将匹配的结果转换为字符串。在for循环中,我们使用string.rep函数来构造由问号组成的字符串,并使用str:match函数对该字符串进行匹配。在最后一个print语句中,我们对字符串"?????foobar???foo?bar???"进行匹配,打印出匹配的结果。

2020-11-27 09:36:03