Search code examples
stringlualua-patterns

Lua pattern for parsing strings with optional part


I have to parse a string in the form value, value, value, value, value. The two last values are optional. This is my code, but it works only for the required arguments:

Regex = "([^,])+, ([^,])+, ([^,])+" 

I'm using string.match to get the value into variables.


Solution

  • Since you're splitting the string by a comma, use gmatch:

    local tParts = {}
    for sMatch in str:gmatch "([^,]+)" do
        table.insert( tParts, sMatch )
    end
    

    Now, once the parts are stored inside the table; you can check if the table contains matched groups at indexes 4 and 5 by:

    if tParts[4] and tParts[5] then
        -- do your job
    elseif tParts[3] then
        -- only first three matches were there
    end