在字符串中查找一组已定义的值

我试图在一个字符串中查找一组值,并且只有当字符串与一组值完全匹配时,才返回该值。

我的原始表达式如下:

title = "MrS"
setTitles = {"Miss", "Mr", "Mrs", "Dr", "Ms"}
title = (title:gsub("%w",string.lower)):gsub("^l", string.upper)

if string.match(title, setTitles) ~= nil then title = title else title = "XX" end

然后我意识到我需要一些方法循环遍历这些值,因此到达了这里:

title = "MrS"
setTitles = {"Miss", "Mr", "Mrs", "Dr", "Ms"}
title = (title:gsub("%w",string.lower)):gsub("^%l", string.upper)

for i = 1, 5 do
  if string.match(title, setTitles[i]) ~= nil
    then title = title
  else title = "XX"
  end
end

然而,每次都只返回 "XX"

我知道这可能相当简单和明显,但我似乎找不到解决方法,真的很需要帮助!

点赞
用户7396148
用户7396148

下面是为什么您的代码无法运行的原因。您循环的第一次使用了 Mrs 并检查它是否匹配 Miss,但实际上并没有匹配,因此它将 title 更改为 XX,因此以后的所有检查都无法匹配。

在检查所有可能的值之前,您不能更改 title。 通过调整您的代码,使用 matchFound 变量来确定是否需要更改,您可以解决此问题:

local matchFound = false
for i = 1, 5 do
  if string.match(title, setTitles[i]) ~= nil then
    matchFound = true
    break
  end
end
if matchFound == false then
  title = "XX"
end
print(title)

另外,您的代码可以将 Mr 误匹配为 Mrs,原因是 Mr 将匹配到 Mrs 中或以 Mr 开头的任何字符串。要更改此设置,您可以调整对 string.match 的调用:

string.match(title, "^".. setTitles[i] .. "$")

这强制 string.match 确保模式的第一个和最后一个字符也是传递给它的字符串的第一个和最后一个字符。


建议使用 setTitles 创建一个真正的设置,而不是使用 string.match

local setTitles = {["Miss"] = true, ["Mr"] = true, ["Mrs"] = true, ["Dr"] = true, ["Ms"] = true}

然后您的检查变成了:

title = setTitles[title] and title or "XX"

有关 Lua 资源设置的说明:

https://www.lua.org/pil/11.5.html

http://lua-users.org/wiki/SetOperations

2019-06-27 14:52:31
用户870125
用户870125

你不应该在 for 循环中更改 title 变量。

你可以尝试这段代码:

--title = "MrS"
title = "MrX"
setTitles = {"Miss", "Mr", "Mrs", "Dr", "Ms"}
title = title:gsub("%w", string.lower) -- 把 title 变成小写
title = title:gsub("^%l", string.upper) -- 把 title 变成开头大写

ismatch = false

for i = 1, 5 do

    print(title, setTitles[i])

    if tostring(title) == tostring(setTitles[i]) then
        ismatch = true
        print("匹配成功")
        return
    end

end

if ismatch then title = title else title = "XX" end
print(title)

希望这可以帮到你。

2019-06-27 14:57:58