跳转到内容

模組:CategoriesParser

维基百科,自由的百科全书
local p = {}

function p._parseCategory( text )
	local result = {}

	function replaceFunc( cat )
		local split = mw.text.split( cat, "|" )
		local title = split[ 1 ]
		table.remove( split, 1 )
		table.insert( result, {
			title = mw.title.new( mw.text.trim( title ), 14 ).text,
			patten = table.concat( split, "|" )
		} )
		return ""
	end

	text = text
		:gsub( "%[%[:?[Cc][Aa][Tt][Ee][Gg][Oo][Rr][Yy]:(.-)%]%]", replaceFunc )
		:gsub( "%[%[:?[Cc][Aa][Tt]:(.-)%]%]", replaceFunc )
		:gsub( "%[%[:?分[類类]:(.-)%]%]", replaceFunc )
		
	return result, text
end

function p.main( frame )
	local text = frame.args.text
	local format = frame.args.format -- ex: [[:Category:$1|$2]], $1: title, $2: patten
	local categories = p._parseCategory( text )
	local wt = ""
	
	for _, v in ipairs( categories ) do
		wt = wt .. format:gsub( "$1", v.title ):gsub( "$2", v.patten ):gsub( "|]]", "]]" ) -- fix [[Category:$1|$2]]
	end
	
	return wt
end
return p