Lua:string.rep嵌套在string.gsub内?

问题描述:

我希望能够采取一个字符串,并重复每个子字符串后面的数量的次数,而删除号码。例如“5北,3西” - >“北北北北,西西西”。这是我试过的:Lua:string.rep嵌套在string.gsub内?

test = "5 north, 3 west" 
test = test:gsub("(%d) (%w+)", string.rep("%2 ", tonumber("%1"))) 
Note(test) 

但我只是得到一个错误,如“预计数量为零”。

您需要使用一个函数作为第二个参数gsub

test = "5 north, 3 west" 
test = test:gsub("(%d) (%w+)", 
    function(s1, s2) return string.rep(s2.." ", tonumber(s1)) end) 
print(test) 

这将打印north north north north north , west west west

+0

猜猜我甚至不需要使用tonumber()。或者我应该使用它呢? – 2015-01-31 20:51:26

+0

它在Lua 5.1中对我来说没有使用tonumber,但它并没有受到伤害。 – 2015-01-31 20:58:05

为了改善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)之前