Lua - 使用模式提取字符串

时间:2012-07-07 13:46:44

标签: string lua lua-patterns

我刚开始使用Lua Patterns。

我有一个字符串 |2|34|56|1

如何从字符串中提取数字?

我可以手动解析字符串并排除所有“|”字符。但我确信使用Lua模式会更简单。

在这种情况下,模式有何帮助?

1 个答案:

答案 0 :(得分:3)

如果您只想打印这些数字,最好的方法是:

str = "|2|34|56|1"
str:gsub("%d+", print)

否则,如果您希望将数字存储在表格中,则需要更长的方法:

str = "|2|34|56|1"
local tFinal = {}
str:gsub( "%d+", function(i) table.insert(tFinal, i) end)
table.foreach(tFinal, print)        -- This is only to verify that your numbers have been stored as a table.
相关问题