Documentation for this module may be created at Module:Replace/doc
-- <pre>
-- A module to allow substitution of regex replace functions
local p = {}
function p.main(frame)
local args = frame:getParent().args
return p._main(args)
end
-- a : string
-- b : search
-- c : replace
function p._main(args)
local a = mw.text.decode(args[1])
local b = mw.text.decode(args[2] or '')
local c = mw.text.decode(args[3] or '')
-- let us use real regex stuff
local b = mw.ustring.gsub(b,'\\','%')
:gsub('%*%?','-')
local c = mw.ustring.gsub(c,'$(%d)','%%%1')
-- get just the new string
local ret = mw.ustring.gsub(a,b,c)
-- trim whitespace
ret = mw.text.trim(ret)
-- condense whitespace
ret = mw.ustring.gsub(ret,' +',' ')
return ret
end
-- trying to emulate regex's alteration in pattern matches
function p.test(reg)
-- create 2 sets of captures to use
-- one for storage, the other for manipulation
local captures,_captures = {},{}
-- string to perfom the search on
local _s = '55(aa)66(bb)77 7aaaa'
-- string to hold pattern match
local s = reg or '55%(aa%)66%((bb)%)..%s.(aaaa|asas).(aa|45|4444)'
mw.log(s)
mw.log('---')
-- convert parentheses into full width for temp parsing
s = mw.ustring.gsub(s,'%%%(','(')
s = mw.ustring.gsub(s,'%%%)',')')
-- string to use for string.format in tests
-- convert %s to %$ for temp parsing
local _sform = mw.ustring.gsub(s,'%%s','%%$')
-- matches any set of parentheses that isn't started with a %
_sform = string.gsub(_sform,'%f[(%%](%b())','(%%s)')
-- convert full width back to escaped
_sform = _sform:gsub('(','%%('):gsub(')','%%)')
-- double up % since string.format is bitchy
_sform = _sform:gsub('%%([^s])','%%%%%1')
-- turn $ back to s
_sform = _sform:gsub('%%%%%$','%%%%s')
-- finds all parenthetical groups that aren't begun with a %
-- add to table of manipulate-able capture
for v in string.gmatch(s,'%f[(%%](%b())') do
-- match to remove parentheses
table.insert(captures,string.match(v,'^%((.+)%)$'))
end
-- convert each capture into a table
-- split by alteration character
for _, v in ipairs(captures) do
table.insert(_captures,mw.text.split(v,'|'))
end
-- table of all possible combinations used for the formatting
local groupstouse = {}
-- recursive function
local function addtogroups(x,stor)
-- for all in the set
for i, v in ipairs(_captures[x]) do
-- temporary storage
local _stor = {}
-- deep copy because fuck lua
for _, u in ipairs(stor or {}) do
table.insert(_stor,u)
end
-- add current pattern to storage
table.insert(_stor,v)
-- if there's a next group, run func on those
if _captures[x+1] then
addtogroups(x+1,_stor)
-- otherwise just add this to the master table
else
table.insert(groupstouse,_stor)
end
end
end
-- run recursive func
addtogroups(1)
for _, v in ipairs(groupstouse) do
-- if a match is found, use those groups
local formatted = mw.ustring.format(_sform,unpack(v))
-- logging results
mw.log(table.concat(v,' -- ')..' : '..formatted)
end
end
return p