模組:FormatString/doc
跳至導覽
跳至搜尋
此頁面為 Module:FormatString 的說明文件
這是一個進行字符串格式化的模塊,採用AC自動機作為字符串匹配算法。
與string.format相比,支持自定義占位符。與使用string.gsub進行匹配與替換相比,在模式串較多時有速度優勢。
方法
buildTrie(format)
功能
將格式化參數列錶轉化為一個字典樹。這個字典樹可以反覆使用。
參數
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進行格式化。
參數
str:待格式化的字符串。trie:建立的字典樹。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
未實現的功能
- 占位符中包含統配符或正則表達式以匹配參數。