Lua - 使用模式提取字符串

我刚开始学习 Lua 模式。

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

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

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

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

点赞
用户1190388
用户1190388

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

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.
2012-07-07 14:21:58