Lua:string.rep嵌套在string.gsub中?
我想能够采取一个字符串,并重复每个子字符串后面的数字,该数量的次数,同时删除该数字。例如“5北,3西”->“北-北-北,西-西”。这就是我所尝试的:Lua:string.rep嵌套在string.gsub中?,string,lua,gsub,repeat,String,Lua,Gsub,Repeat,我想能够采取一个字符串,并重复每个子字符串后面的数字,该数量的次数,同时删除该数字。例如“5北,3西”->“北-北-北,西-西”。这就是我所尝试的: test = "5 north, 3 west" test = test:gsub("(%d) (%w+)", string.rep("%2 ", tonumber("%1")) ) Note(test) 但是我只得到了一个错误,比如“number expected get Nil。”您需要使用一个函数作为第二个参数来gsub: test = "
test = "5 north, 3 west"
test = test:gsub("(%d) (%w+)", string.rep("%2 ", tonumber("%1")) )
Note(test)
但是我只得到了一个错误,比如“number expected get Nil。”您需要使用一个函数作为第二个参数来
gsub
:
test = "5 north, 3 west"
test = test:gsub("(%d) (%w+)",
function(s1, s2) return string.rep(s2.." ", tonumber(s1)) end)
print(test)
这将打印出
北、西、西
,以改进Kulchenko的答案:
test = "5 north, 3 west"
test = test:gsub("(%d+) (%w+)",
function(s1, s2) return s2:rep(tonumber(s1),' ') end)
print(test)
改进:
- 逗号前没有空格
- 允许数字超过9(%d+)而不是(%d)