3

I have quite simple question, but my google research did not help.. I am pretty new to Lua, so..

I have string "XXXX_YYYYYY_zzzzzz" stored in local variable and I want to parse it and get 3 new local variables. Should I use string.find?

local str_ = "XXXX_YYYYY_zzzzzz"    
local first_, second_, third_ = strind.find(str_, "^(%w+)_(%w+)_(%w+)$")

1 Answer 1

5

Use string.match instead:

local str_ = "XXXX_YYYYY_zzzzzz"    
local first_, second_, third_ = str_:match "^([^_]+)_([^_]+)_([^_]+)$"

Have a look at the string library on lua-users wiki.

string.find would additionally return the indexes where the matched substring was located/found. These two (start and end) indices are not useful to your case, which is why string.match would be a better tool.

Sign up to request clarification or add additional context in comments.

2 Comments

Instead of %w+, you can use .- just in case the fields contain punctuation.
@lhf I'd rather go with [^_]. Anyway, these speculations would depend on more input from OPs side.

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.