2012-07-07 71 views
0

我刚刚开始使用Lua模式。Lua - 使用模式提取字符串

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

我如何提取字符串中的数字?

我可以手动解析字符串,并排除所有'|'字符。但我确定使用Lua模式会简单得多。

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

回答

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. 
+0

谢谢!如果存在一些字符串,那么解决方案是什么? 像'“| 2 | 34 | a | 1 | ba”' – SatheeshJM 2012-07-07 14:52:09

+0

是!如果你有浮点数,它只会失败。 – hjpotter92 2012-07-07 15:10:30

+0

编号。我的意思是如果字符串是'| 2 | 34 | a | 1 | ba',我也想提取字符串。 我需要提取'2','34',''a“,'1','”ba“'这可能吗? – SatheeshJM 2012-07-07 15:16:58