• Moegirl.ICU:萌娘百科流亡社群 581077156(QQ),欢迎对萌娘百科运营感到失望的编辑者加入
  • Moegirl.ICU:账号认领正在试运行,有意者请参照账号认领流程

模組:FormatString/doc

萌娘百科,萬物皆可萌的百科全書!轉載請標註來源頁面的網頁連結,並聲明引自萌娘百科。內容不可商用。
跳至導覽 跳至搜尋

此頁面為 Module:FormatString 的說明文件

這是一個進行字符串格式化的模塊,採用AC自動機作為字符串匹配算法。

與string.format相比,支持自定義佔位符。與使用string.gsub進行匹配與替換相比,在模式串較多時有速度優勢。

方法

buildTrie(format)

功能

將格式化參數列錶轉化為一個字典樹。這個字典樹可以反覆使用。

參數

  1. format:格式化參數列表,是一個Lua的table,並具有如下形式:
{
    {
        format = "%d",
        callback = function(matched_times, extras) 
            mw.log('%d matched')
            return tostring(extras[matched_times]) 
        end
    },
    {
        format = "%f",
        callback = function(matched_times, extras) 
            mw.log('%f matched')
            return tostring(extras[matched_times]) 
        end
    },
    ...,
    {
        format = "%s",
        callback = function(matched_times, extras) 
            mw.log('%s matched')
            return tostring(extras[matched_times]) 
        end
    }
}

其中,format代表待匹配的佔位符。

當匹配到某一個佔位符時,對應的callback函數將會被調用。此函數應該返回一個字符串,原先的佔位符將被這個字符串替換。

callback函數的第一個參數matched_times表示這是第幾次匹配到佔位符;第二個參數extras為附加數據,通常是待填充的真實值。

需要注意的是,某一個佔位符不應該是另一個佔位符的前綴,如以下寫法是不合法的:

{
    {
        format = "her",
        callback = ...
    },
    {
        format = "he",      -- he是her的一个前缀
        callback = ...
    }
}

返回值

建立的字典樹。

replaceStr(str, trie, extras)

功能

對字符串str進行格式化。

參數

  1. str:待格式化的字符串。
  2. trie:建立的字典樹。
  3. extras:附加數據,通常是待填充的真實值。你非要用全局變量我也沒辦法。

返回值

格式化完成後的字符串。

例子

local FormatString = require("Module:FormatString")
local formatList = {
    {
        format = "%d",
        callback = function(matched_times, extras) 
            return tostring(extras[matched_times]) 
        end
    },
    {
        format = "%f",
        callback = function(matched_times, extras) 
            return tostring(extras[matched_times]) 
        end
    },
    {
        format = "%X",
        callback = function(matched_times, extras) 
            return string.format('%X', extras[matched_times])
        end
    }
}
local trie = FormatString.buildTrie(formatList)
mw.log(FormatString.replaceStr('%d %f', trie, { 1, 0.25 }))
mw.log(FormatString.replaceStr('%d,%X,%f', trie, { 5, 10, 2.33 }))

預期輸出:

1 0.25
5,A,2.33

未實現的功能

  1. 佔位符中包含統配符或正則表達式以匹配參數。