Use string.gsub to replace strings, but only whole words

前端 未结 2 642
借酒劲吻你
借酒劲吻你 2021-01-05 13:24

I have a search replace script which works to replace strings. It already has options to do case insensitive searches and \"escaped\" matches (eg allows searching for % ( et

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-05 14:30

    do you mean if you pass nocase() foo, you want [fooFOO] instead of [fF][oO][oO]? if so, you could try this?

    function nocase (s)
          s = string.gsub(s, "(%a+)", function (c)
                return string.format("[%s%s]", string.lower(c),
                                               string.upper(c))
              end)
          return s
    end
    

    and if you want an easy way to split a sentence into words, you can use this:

    function split(strText)
        local words = {}
        string.gsub(strText, "(%a+)", function(w)
                                        table.insert(words, w)
                                      end)
        return words
    end
    

    once you've gotten the words split, it's pretty easy to iterate over the words in the table and do a full comparison against each word.

提交回复
热议问题