LUA 嵌套表中的模式匹配

我想在下面的表中执行模式匹配。如果匹配成功,将第二列和第三列的值作为答案。第一列可以有一个或多个模式,第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
点赞
用户234175
用户234175

你的代码看起来大部分都是正确的,但是你使用的模式有一点偏差。你没有得到预期的索引,因为所有的模式都期望在匹配单词时包含连字符(由于你的模式中的 %-)。

正如 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 -- 匹配第 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>
2020-03-02 05:24:24