Module:ReplacePlus

From EarthMC
Jump to navigation Jump to search

Documentation for this module may be created at Module:ReplacePlus/doc

local module = {}
 
local getArgs = require('Module:Arguments').getArgs
 
function _main(args, frame)
	local str = args['str'] or args[1] or ''
	local ptn = args['ptn'] or args[2] or ''
	ptn = mw.text.decode(mw.text.unstripNoWiki(ptn))
	local replace = args['rep'] or args[3] or ''
	local split = args['spl'] or args[4] or '、'
	local limit = args['lim'] or args[5] or 'false'
	local origin = tonumber(args['ori'] or args[6] or 1)
	local noprint = args['noprint'] or false
	
	str = mw.ustring.sub(str, origin)
	
	local captures = {}
	local result, count = ''
	
	if string.find(limit, '%d+') then
		limit = tonumber(limit)
		result, count = mw.ustring.gsub(str, ptn, function(s)
			captures[#captures + 1] = s
			return s
		end, limit)
		result = mw.ustring.gsub(str, ptn, replace, limit)		
	else
		result, count = mw.ustring.gsub(str, ptn, function(s)
			captures[#captures + 1] = s
			return s
		end)
		result = mw.ustring.gsub(str, ptn, replace)		
	end
	
	frame:callParserFunction('#vardefine', 'result.capture', table.concat(captures, split))
	frame:callParserFunction('#vardefine', 'result.count', count)
	
	if noprint ~= 'true' then
		return result		
	else
		frame:callParserFunction('#vardefine', 'result', result)
		return ''
	end
end
 
function module.main(frame)
	local args = getArgs(frame)
	return _main(args, frame)
end
 
function module.multi(frame)
	local args = getArgs(frame, { warppers = 'Template:Str_replace_multi' } )
	local text = args[1] or ''
	local done = {}
	if args[2] then
		local sort = mw.text.split(mw.ustring.gsub(args[2], '|+', '|'), '|')
		while sort[#sort] == '' do
			table.remove(sort, #sort)
		end
		for _, key in ipairs(sort) do
			if key ~= 1 and key ~= 2 then
				text = mw.ustring.gsub(text, key, args[key])
			end
			done[key] = true
		end
	end
	-- 允许对顺序不依赖的情况直接使用模块
	for key, val in pairs(args) do
		if not done[key] and key ~= 1 and key ~= 2 then
			text = mw.ustring.gsub(text, key, val)
		end
	end
	return text
end
 
return module