模块:FormatString

来自维阿百科
跳转至: 导航搜索

此模块的文档可以在模块:FormatString/doc创建

local queue = require("Module:queue")

local FormatString = {}

function FormatString.buildTrie(format)
    root = {}
    root.next = {}
    for i, item in ipairs(format) do
        local cur = root
        for i = 1, mw.ustring.len(item.format), 1 do 
            local c = mw.ustring.sub(item.format, i, i)
            if cur.next[c] == nil then
                cur.next[c] = {} -- new node
                cur.next[c].next = {} 
                cur.next[c].father = cur
                cur.next[c].char = c
            end
            cur = cur.next[c]
        end
        cur.callback = item.callback
        cur.len = mw.ustring.len(item.format)
    end
    root.fail = {}
    local q = queue
    q:push(root)
    while not(q:empty()) do
        local cur = q:front()
        q:pop()
        for i, t in pairs(cur.next or {}) do
            q:push(t)
        end
        if (cur ~= root) and (cur.father ~= root) then
            cur2 = cur.father
            while cur2.fail.next[cur.char] ~= nil and cur2 ~= root do
                cur2 = cur2.fail
            end
            cur.fail = cur2.fail.next[cur.char] or root
        else
            cur.fail = root
        end

    end
    return root
end

function FormatString.replaceStr(str, trie, extras)
    local cur_state = trie
    local i = 1
    local matched_times = 0
    while i <= mw.ustring.len(str) do
        local c = mw.ustring.sub(str, i, i)
        while cur_state.next[c] == nil and cur_state ~= trie do
            cur_state = cur_state.fail or trie
        end
        cur_state = cur_state.next[c] or trie
        if cur_state.callback ~= nil then
            matched_times = matched_times + 1
            local newStr = cur_state.callback(matched_times, extras)
            -- mw.log(mw.ustring.sub(str, i - cur_state.len + 1, i)..' -> '..newStr)
            str = mw.ustring.sub(str, 1, i - cur_state.len)..newStr..mw.ustring.sub(str, i + 1, mw.ustring.len(str))
            i = i + mw.ustring.len(newStr) - cur_state.len
            cur_state = trie
        end
        i = i + 1
    end
    return str
end

return FormatString