How can I find the words consist of the letters inside the keyword in Lua?

后端 未结 3 515
北恋
北恋 2021-01-24 02:30

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 t

3条回答
  •  我在风中等你
    2021-01-24 03:17

    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?

    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
    

    Output:

    done    matches
    abandon matches
    band    matches
    bane    matches
    dane    matches
    danger  does not match
    rand    does not match
    bade    matches
    rand    does not match
    

提交回复
热议问题