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

我想能够将一个字符串中每个数字后面的子字符串重复该数字所表示的次数,同时删除数字。例如,"5 north, 3 west" --> "north north north north north, west west west"。我尝试了以下代码:

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

但是我收到了一个像 "number expected got Nil." 的错误信息。

点赞
用户1442917
用户1442917

你需要将一个函数作为 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

2015-01-31 20:42:09
用户3735873
用户3735873

为了稍微改进 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)
2015-02-01 15:57:42