0

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?

1 Answer 1

4

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.
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! if some strings were present what would be the solution then? Like "|2|34|a|1|ba"
NO. I mean if the string was |2|34|a|1|ba, I'd like to extract the strings as well. I need to extract 2,34,"a",1,"ba" Is that possible?
@SatheeshJM, use "[^|]+" instead of "%d+".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.