arrays - 嵌套表中的 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>
推荐阅读
- python - 我正在制作一个机器人,它喜欢所有尚未被喜欢的帖子
- swift - 设置在 UIableView 中突出显示的默认单元格
- django - 如何修复“包含的 URLconf 'gp.urls' 中似乎没有任何模式”
- android - Firebase 身份验证 - 开源 Android 应用
- python - 处理由ajax发送到龙卷风的复杂数据的最佳方法
- python - 如何在我的 google chromebook 上获取 python?
- python - 如何根据 Python 中的 csv 文件仅选择我想要的列导入多个 csv 文件
- c# - C# MongoClient 在第二次请求后抛出 DnsResponseException
- c# - 线程在操作系统上下文中的作用是什么?
- node.js - Parse Sever with custom Express app Master Key Permission Denied