Search code examples
stringlualua-patterns

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?


Solution

  • 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.