【问题标题】:string.match is too broad, is there any other alternatives that would work better?string.match 太宽泛了,还有其他更好的选择吗?
【发布时间】:2020-11-03 13:59:15
【问题描述】:

目前,我正在将一堆字符串从家庭自动化控制器传递给我目前正在开发的驱动程序。
我收到诸如ZAA 之类的消息和其他可能是AA 的代码,但string.match 有时会将AAZAA if 语句相匹配。

这个问题的传播范围远不止这两个字符串(可能大约有 10-15 个其他相似之处)。
我知道我可以在 if/elseif 语句中添加更多条件,但肯定有 exact 匹配版本吗?

任何想法将不胜感激。

示例; 即使字符串是“AA”,它也会匹配“ZAA”

stringInput = "AA"

if string.match("ZAA", stringInput) then
    print("I matched: ZAA")
elseif string.match("AA", stringInput) then 
    print("I matched: AA")
end

【问题讨论】:

  • 您的输入看起来如何?如果它以模式开头,那么你可以简单地匹配'^AA'。否则,您能否添加一些示例输入?
  • 尝试反转参数:string.match(stringInput,"ZAA").

标签: lua scripting


【解决方案1】:

如果您想要精确匹配,只需使用==

if stringInput == 'ZAA' then
    print('I matched: ZAA')
elseif stringInput == 'AA' then
    print('I matched: AA')
end

【讨论】:

  • 这可能是我的答案,并且非常有意义......我实际上不知道为什么我不使用这些运算符,它只是我们为另一家公司编写的类似驱动程序的副本。我明天试试这个!
【解决方案2】:

来自Lua 5.3. Reference Manual: string.match

string.match(s, pattern [, init]) 在字符串 s 中查找模式的第一个匹配项(参见 §6.4.1)。如果找到一个,则匹配 从模式返回捕获;否则返回零。如果 模式指定不捕获,然后返回整个匹配。一种 第三,可选的数字参数 init 指定从哪里开始 搜索;它的默认值为 1,可以为负数。

所以

local inputString = "AA"
string.match("ZAA", inputString)

将匹配,因为 "AA""ZAA" 中。

您混淆了函数参数spattern

本地输入字符串 = "AA" inputString:match("ZAA")

将不匹配,因为该模式包含的字符多于 inputString。

但是作为

local inputString = "ZAA"

两者都匹配

inputString:match("AA")inputString:match("ZAA") 您可能需要添加更多约束。

请阅读说明书!

【讨论】:

    猜你喜欢
    • 2011-04-21
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多