这个问题与此有点相似,但我的任务是使用gsub
函数在重复字符(例如问号(之间放置一些东西,在我的情况下是破折号。
示例:
"?" = "?"
"??" = "?-?"
"??? = "?-?-?"
试试这个:
function test(s)
local t=s:gsub("%?%?","?-?"):gsub("%?%?","?-?")
print(#s,s,t)
end
for n=0,10 do
test(string.rep("?",n))
end
使用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???"))
这是我通过逐个字母扫描每个字母得出的结果
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