模块:ReplacePlus

来自东方活动维基
稀神灵梦留言 | 贡献2024年5月26日 (日) 23:21的版本 (创建页面,内容为“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…”)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

可在模块: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

return module