You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lua中如何实现不区分大小写的子字符串搜索

Lua实现不区分大小写的子字符串搜索

要解决原代码只能匹配小写开头键的问题,有两种实用方案:

方案1:统一转换为小写(兼容所有Lua版本)

将表的键和搜索字符串都转为小写后再匹配,彻底忽略大小写差异:

a = {["hello"] = 1, ["Hello"] = 2}

for key in pairs(a) do
    if string.find(string.lower(key), string.lower("h")) then
        print(key)
    end
end

运行后会输出hello和Hello,该写法适配所有Lua版本,兼容性拉满。

方案2:使用模式修饰符(Lua 5.3+)

Lua 5.3及以上版本支持在匹配模式中加入(?i)修饰符,直接开启不区分大小写匹配,写法更简洁:

a = {["hello"] = 1, ["Hello"] = 2}

for key in pairs(a) do
    -- (?i) 修饰符让后续模式匹配不区分大小写
    if string.find(key, "(?i)h") then
        print(key)
    end
end

这种方案无需额外字符串转换,直接通过模式语法实现需求。

内容的提问来源于stack exchange,提问作者NEKKITIS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 03:50:28