KarimS
KarimS

Reputation: 3902

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.

Upvotes: 1

Views: 1062

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174874

In Lua you can't make a capturing group optional, and also you are not able to use a logical OR operator. So the answer is: It isn't possible.

Upvotes: 1

hjpotter92
hjpotter92

Reputation: 80653

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

Upvotes: 2

Related Questions