如何在Lua中找到由关键字内的字母组成的单词? [英] How can I find the words consist of the letters inside the keyword in Lua?
问题描述
例如,我有一个关键字"abandoned",我想从存储这些单词的数组中找到包含该关键字字母的单词,例如"done","abandon",band".搜索吗?
For example, I have a keyword "abandoned" and I want to find the words that contains letters of this keyword such as "done", "abandon", band", from the arrays I stored those words. How can I search it?
我尝试编写此代码,但无法正常工作.我写了一个包含关键字和单词的函数.然后我将关键字字母放到keywordletters数组中,然后将单词字母放到wordletters数组中.
I tried to write this code but not working properly. I wrote a function which takes the keyword and the word. Then i put letters of keyword to keywordletters array and the letters of the word into wordletters array.
然后我写了一个匹配字母的循环.如果wordletters数组与keywordletters数组的字母匹配,则我将当前wordletters元素分配为nil,然后将keywordletters元素设置为nil.因为我们不能第二次使用它.
Then i wrote a loop for matching letters. If the wordletters array match with the letter of keywordletters array, then i assigned the current wordletters element nil and then i made the keywordletters element nil. Because we can't use it second time.
在所有循环之后,我检查了wordletters数组.如果它有一个不是nil的元素,那么我返回false.但是,我不想要它.你能帮我吗?
After all loops, i checked the wordletters array. If it has an element which is not nil then i returned false. However, it's not working how i want. Can you help me out?
ı我解决了我的问题,并相应地编辑了代码.
ıI solved my problem and edited the code accordingly.
这是我的代码:
function consistLetters(keyword,word)
keywordletters={ }
wordletters= { }
local found=false
findLetters(keyword,keywordletters)
findLetters(word,wordletters)
for i=1, #wordletters,1 do
for j=1, #keywordletters,1 do
if(keywordletters[j]~="") then
if(wordletters[i]==keywordletters[j]) then
keywordletters[j]=""
found=true;
break
end
end
end
if found~=true then
return false
end
found=false;
end
end
推荐答案
例如,我有一个关键字"abandoned",我想从存储这些单词的数组中找到包含该关键字字母的单词,例如"done","abandon",band".搜索吗?
For example, I have a keyword "abandoned" and I want to find the words that contains letters of this keyword such as "done", "abandon", band", from the arrays I stored those words. How can I search it?
您可以简单地使用关键字作为正则表达式(在Lua中也称为模式"),将其字母作为一组,例如('^[%s]+$'):format('abandoned'):match('done')
.
You can simply use the keyword as a regular expression (aka "pattern" in Lua), using it's letters as a set, for instance ('^[%s]+$'):format('abandoned'):match('done')
.
local words = {'done','abandon','band','bane','dane','danger','rand','bade','rand'}
local keyword = 'abandoned'
-- convert keyword to a pattern and match it against each word
local pattern = string.format('^[%s]+$', keyword)
for i,word in ipairs(words) do
local matches = word:match(pattern)
print(word, matches and 'matches' or 'does not match')
end
输出:
done matches
abandon matches
band matches
bane matches
dane matches
danger does not match
rand does not match
bade matches
rand does not match
这篇关于如何在Lua中找到由关键字内的字母组成的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!