Lua string.match...在单词匹配时,可以在结尾加上可选标点符号。

好的,我刚学Lua语言。

我正在尝试通过一些字符串匹配,但如果在我的“句子字典”中的单词后面有任何标点符号,匹配就不起作用了。

我原以为添加“%p?”会匹配“零个或一个标点符号”,但事实并非如此?

local string_that_matches = string.match(Dictionary[i], textsubmitted..'%p?')

编辑:添加更多信息。这是完整的例程:

嗯...好吧,我只是检查string_that_matches是否为空...如果不是,则将它添加到新的匹配数组中,因为我们正在遍历约50个项目:

local dictSize = table.maxn(Dictionary)
matches = {} -- new array to hold matches

for i=1,dictSize do -- Loop through dictionary items
    local string_that_matches = string.match(Dictionary[i],textsubmitted..'%p?')
    if string_that_matches ~= nil then
        table.insert(matches, Dictionary[i])
    end
end
return matches
点赞
用户1442917
用户1442917

以下所有组合都如我所预期地匹配:

string.match("Good night, boys and girls.", "night")

将返回 night

string.match("Good night, boys and girls.", "night%p?")

将返回 night,

如果你希望匹配不包含(可选的)标点符号,则将 textsubmitted 包含在括号中:

string.match("Good night, boys and girls.", "(night)%p?")

这将返回 night

以下是一个完整的示例,你可以进行尝试:

local Dictionary = {"Good night, boys and girls."}

function trymatch(textsubmitted)
  local dictSize = table.maxn(Dictionary)
  matches = {} -- 创建一个新的数组来存储匹配项

  for i=1,dictSize do -- 遍历字典
    local string_that_matches = string.match(Dictionary[i],textsubmitted..'%p?')
    if string_that_matches ~= nil then
      table.insert(matches, Dictionary[i])
    end
  end
  return matches
end

print(trymatch("Good")[1])
print(trymatch("night")[1])
print(trymatch("boys")[1])
print(trymatch("nothing")[1])

如预期打印:

Good night, boys and girls.
Good night, boys and girls.
Good night, boys and girls.
nil
2014-07-19 01:55:49