首页 > 解决方案 > 嵌套表中的 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

标签: arraysluapattern-matching

解决方案


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

正如 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>


推荐阅读