SatheeshJM
SatheeshJM

Reputation: 3643

Lua - extract a string using patterns

I'm just starting on Lua Patterns.

I have a string |2|34|56|1

How do I extract the numbers from the string?

I can parse the string manually and exclude all the '|' characters. But I'm sure using Lua patterns will be much simpler.

How do patterns help in this case?

Upvotes: 0

Views: 3731

Answers (1)

hjpotter92
hjpotter92

Reputation: 80653

If you only want to print those numbers, the best method is:

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

Else, if you want the numbers to be stored in a table, a longer approach is required:

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.

Upvotes: 4

Related Questions