Search code examples
stringluastring-matchinglua-patterns

Lua string.find correct format?


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+)$")

Solution

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