好吧,我对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
发布于 2014-07-18 17:55:49
所有这些组合都符合我的预期:
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
https://stackoverflow.com/questions/24835919
复制相似问题