Lua - 如何在字符串中使用变量 %d 条件语句?

我想比较一个字符串是否符合某个模式(注意字符串后面没有其他内容!),并且字符串中包含一个数字(但不知道是多少)。

我写了这个函数,但它在某些情况下不起作用,我认为已经有解决方案了。

function Match(string, pattern)
    local start , final = string.find(string,pattern)
    local len = string.len( string )
    if len == final then return true else return false end
end

我像这样调用它

    if Match(item_loop_name,"!MEx CH %d+ %- "..name) == true then
        --bla bla bla doing something
    end

问题是我的变量名有时会包含特殊字符,比如 -!%,它会影响 string.find 的功能。

非常感谢!

点赞
用户2858170
用户2858170

如果你想确保你的模式被找到在字符串的结尾,你可以使用 $ 将你的模式锚定在字符串的结尾。

local str = "I own 3 pigs and a cow"

"I own %d+ pigs" 会匹配。

"I own %d+ pigs$" 不会匹配。

所以,你可以简单地做如下检查代替检查字符位置:

local stringOk = yourString:match("yourPattern$") and true or false

或者

local stringOk = yourString:find("yourPattern$") and true or false

请参阅 Lua 手册!

请注意,在没有字符串示例的情况下不能提供进一步的帮助。

2020-12-20 09:14:48