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

Lua中如何禁止字母输入仅允许数字?及正则匹配指定格式问题

Lua 相关问题解答

1. 如何在Lua中禁止字母输入,仅允许输入数字?

如果是从控制台获取用户输入,可通过循环校验确保输入全为数字:

local validInput
repeat
    io.write("请输入数字:")
    validInput = io.read()
-- 校验输入是否为纯整数,若需支持浮点数,可改用 "^%d*%.?%d+$"
until validInput:match("^%d+$")
print("有效数字输入:" .. validInput)

如果是校验已有字符串是否仅含数字,直接用模式匹配判断即可:

local myStr = "12345"
if myStr:match("^%d+$") then
    print("该字符串仅含数字")
else
    print("字符串包含非数字字符")
end

2. 如何正确校验字符串是否符合 number|number|string 格式?

你之前的代码问题在于:模式 [%d]|[1-2]|. 是三个独立的匹配分支,只要字符串中存在单个数字、1/2或任意单个字符就会返回匹配成功,且未锚定整个字符串,导致不符合格式的内容也会被误判。

正确的模式需要锚定字符串的开头和结尾,确保整体结构完全匹配 数字|数字|任意非|字符(若字符串部分允许包含|,可将[^|]+改为.*):

-- 校验整数格式的示例
local function checkFormat(myStr)
    if string.match(myStr, "^%d+|%d+|[^|]+$") then
        print("yes")
    else
        print("no")
    end
end

checkFormat("1|2|abc") -- 输出 yes
checkFormat("a1|2|abc") -- 输出 no
checkFormat("123|456|hello world") -- 输出 yes

若需支持浮点数(如1.5|3.14|test),可将模式中的%d+替换为%d*%.?%d+:

if string.match(myStr, "^%d*%.?%d+|%d*%.?%d+|[^|]+$") then
    -- 符合格式逻辑
end

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 02:57:40