【问题标题】:LUA pattern matching in nested table嵌套表中的 LUA 模式匹配
【发布时间】:2020-03-01 20:28:26
【问题描述】:

我想在下表中进行模式匹配。如果匹配,则取第二列和第三列的值作为答案。第一列可以有 1 个或多个模式,第 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

【问题讨论】:

  • 如果你只想返回第三列作为函数的结果,那么第二列有什么意义呢?另外,我认为您不需要 %-small%- 或 %-medium%- 中的 %- 等。如果您只是在较大的单词中匹配单词 'small',则模式 small 将工作。

标签: arrays lua pattern-matching


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2022-01-11
    • 1970-01-01
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    • 2013-01-19
    • 2011-02-03
    • 2019-03-29
    • 2011-08-11
    相关资源
    最近更新 更多