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

前端 未结 2 641
借酒劲吻你
借酒劲吻你 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:29

    have a way of doing what I want now, but it's inelegant. Is there a better way?

    There is an undocumented feature of Lua's pattern matching library called the Frontier Pattern, which will let you write something like this:

    function replacetext(source, find, replace, wholeword)
      if wholeword then
        find = '%f[%a]'..find..'%f[%A]'
      end
      return (source:gsub(find,replace))
    end
    
    local source  = 'test testing this test of testicular footest testimation test'
    local find    = 'test'
    local replace = 'XXX'
    print(replacetext(source, find, replace, false))  --> XXX XXXing this XXX of XXXicular fooXXX XXXimation XXX    
    print(replacetext(source, find, replace, true ))   --> XXX testing this XXX of testicular footest testimation XXX
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题