1. 程式人生 > 其它 >Lua-"invalid pattern capture"-實現防注入的string.replace函式

Lua-"invalid pattern capture"-實現防注入的string.replace函式

起因

上線的遊戲,有個俄語玩家提bug說聊天介面崩潰了,登上去看了下並沒有出現問題,於是直接去撈日誌,發現了invalid pattern capture的錯誤日誌,於是請教度娘,找到了答案,可能是匹配引數中的pattern包含了括號
遊戲聊天系統裡面有@功能,處理過程需要用到string.gsub匹配替換玩家名字。暱稱規則中是不允許帶括號的,怎麼會這樣呢?原來是聊天裡面還有個功能,自動翻譯,丫把外文暱稱的某個符號翻譯成了括號,然後匹配的時候就出錯了。

解決

實現自己的替換函式,採用string.find,指定不執行模式匹配。

-- 字串替換【不執行模式匹配】
-- s       源字串
-- pattern 匹配字串
-- repl    替換字串
--
-- 成功返回替換後的字串,失敗返回源字串
string.replace = function(s, pattern, repl)
    local i,j = string.find(s, pattern, 1, true)
    if i and j then
        local ret = {}
        local start = 1
        while i and j do
            table.insert(ret, string.sub(s, start, i - 1))
            table.insert(ret, repl)
            start = j + 1
            i,j = string.find(s, pattern, start, true)
        end
        table.insert(ret, string.sub(s, start))
        return table.concat(ret)
    end
    return s
end

參考

lua下實現防注入的string.replace函式(這位博主的內容不錯,推薦)