用于使用可选部分解析字符串的Lua模式

时间:2014-08-30 10:11:46

标签: string lua lua-patterns

我必须以value, value, value, value, value的形式解析一个字符串。最后两个值是可选的。这是我的代码,但它仅适用于所需的参数:

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

我使用string.match将值转换为变量。

2 个答案:

答案 0 :(得分:2)

由于您要用逗号分割字符串,请使用gmatch

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

现在,一旦零件存储在表格内;您可以通过以下方式检查表中是否包含索引45的匹配组:

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

答案 1 :(得分:0)

Lua中,您无法使捕获组成为可选,并且您也无法使用逻辑OR运算符。所以答案是:这是不可能的。

相关问题