好的,我是Lua语言的新手。
我试图通过一些字符串匹配,但如果在我的"字典"中的单词后面有任何标点符号。句子,这场比赛不起作用。:
我原本以为添加%p?
会匹配"零或一个标点符号",但似乎并非如此?
local string_that_matches = string.match(Dictionary[i], textsubmitted..'%p?')
编辑:添加更多信息。这是完整的例程:
嗯......好吧,我只是检查一下string_that_matches是否为nil ......如果没有,那么将它添加到一个新的匹配数组中,因为我们正在循环约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
答案 0 :(得分:3)
所有这些组合符合预期:
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 = {} -- 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
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