嵌套表中的LUA模式匹配



我想对下表进行模式匹配。如果匹配,则取第2列和第3列的值作为答案。第一列可以有一个或多个图案,第5行只有一个图案可以匹配。

local pattern_matrix = {
{{ "^small%-", "%-small%-",         },   "small",   50},    
{{ "^medium%-", "%-medium%-",       },   "medium",  200},    
{{ "^big%-", "%-big%-",             },   "big",     3},    
{{ "^large%-", "%-large%-", "^L%-", },   "large",   42},             
{{ "%-special%-",                   },   "special", 5},
}

我使用以下代码来查找与输入匹配的行:

local function determine_row(name)
for i = 1,#pattern_matrix,1 do
for _,pattern in pairs(pattern_matrix[i][1]) do  --match against column 1
if name:match(pattern) then 
return i --match found in row i
end
end
end
return 0
end

结果应该是

determine_row("itsamedium") = 2
determine_row("blaspecialdiscount") = 5
determine_row("nodatatomatch") = 0

您的代码看起来基本正确,但您使用的模式有点错误。您没有得到预期的索引,因为所有模式都需要在匹配的单词周围使用连字符。(由于您的图案中的%-(

正如Allister所提到的,如果你想匹配问题的样本输入,你可以把这个单词添加到你的模式列表中。从您的使用情况来看,您甚至可以简化模式。对于不区分大小写的搜索,请在匹配之前对输入使用lower()upper()

例如:

<script src="https://github.com/fengari-lua/fengari-web/releases/download/v0.1.4/fengari-web.js">
</script>
<script type='application/lua'>
local pattern_matrix =
{
{ "small",   50},
{ "medium",  200},
{ "big",     3},
{ "large",   42},
{ "special", 5},
}
local function determine_row(name)
for i, row in ipairs(pattern_matrix) do
if name:match(row[1]) then
return i -- match found in row i
end
end
return 0
end
local test_input = { "itsa-medium-", "itsBiG no hyphen", "bla-special-discount", "nodatatomatch" }
for _, each in ipairs(test_input) do
print( each, determine_row(each:lower())  )
end
</script>

最新更新