Module:Mgsub

--

-- Multiline global substitution: -- Like mw.ustring.gsub, but '^' and '$' match the beginning and end of each -- line, respectively.

return function ( s, pattern, repl, n ) if type( s ) ~= 'string' then error(           'bad argument #1 to \'Dev:Mgsub\' ' ..            '(string expected, got ' .. type( s ) .. ')'       )    end

if type( pattern ) ~= 'string' then error(           'bad argument #2 to \'Dev:Mgsub\' ' ..            '(string expected, got ' .. type( pattern ) .. ')'       )    end

if not ( { ['function'] = 1, table = 1, string = 1 } )[type( repl )] then error(           'bad argument #3 to \'Dev:Mgsub\' ' ..            '(function or table or string expected, got ' .. type( repl ) .. ')'       )    end

if type( n ) ~= 'number' and n ~= nil then error(           'bad argument #4 to \'Dev:Mgsub\' ' ..            '(number expected, got ' .. type( n ) .. ')'       )    end

-- Return the original string if no replacements are allowed. if n ~= nil and n <= 0 then return s, 0 end

-- Only do multiline stuff if there are multiple lines. if mw.ustring.find( s, '\n' ) == nil then return mw.ustring.gsub( s, pattern, repl, n ) end

local updatedString = '' local totalMatches = 0

for line in mw.text.gsplit( s, '\n' ) do       -- Restore newlines removed by mw.text.gsplit. if updatedString ~= '' then updatedString = updatedString .. '\n' end

-- Update the current line if replacements are still allowed. if n == nil or totalMatches < n then local updatedLine, newMatches = mw.ustring.gsub(               line,                pattern,                repl,                n - totalMatches -- remaining replacements            )

updatedString = updatedString .. updatedLine totalMatches = totalMatches + newMatches

-- Add the original line if no more replacements are allowed. else updatedString = updatedString .. line end end

return updatedString, totalMatches end

-- --