Database changes have finished applying - please report any issues you're (still) seeing to support@shoutwiki.com.
Module:MultiReplace
From TechInfoDepot
Jump to navigationJump to search
![]() | Uses Lua: |
For a function to search for multiple patterns, see Template:Ml.
Replaces matches of multiple patterns in a given string with given replacements. For each replacement instance, the pattern matching at the lowest position is chosen. If there are multiple such patterns, then the one specified earliest in the pattern list is chosen.
Usage
{{#invoke:MultiReplace|main|input|plain=yes (optional)|pattern1| replacement1|pattern2|replacement2... }}
If plain=yes
is specified, then the patterns and replacements are treated as plain text, otherwise as Lua Unicode patterns.
The above documentation is transcluded from Module:MultiReplace/doc. (edit | history) Editors can experiment in this module's sandbox (create | mirror) and testcases (create) pages. Subpages of this module. |
1 local p = {}
2
3 local function MultiReplace(args)
4 local input = args[1] or "{{{1}}}"
5 local plain = args.plain == "yes"
6
7 local i = 1
8 local changeList = {}
9 while args[i * 2] do
10 local change = {pattern = args[i * 2], repl = args[i * 2 + 1]}
11 if not change.repl then
12 return require('Module:Error').error{
13 'MultiReplace: Unpaired argument: <code>' .. (i * 2) .. ' = ' .. mw.text.nowiki(change.pattern) .. '</code>'
14 }
15 end
16 changeList[i] = change
17 i = i + 1
18 end
19
20 local matchList = {}
21 local pos = 1
22 local len = mw.ustring.len(input)
23 local result = ""
24 while pos <= len do
25 local bestStart = len + 1
26 local bestStop = len
27 local bestChange
28 for _, change in ipairs(changeList) do
29 local start, stop = mw.ustring.find(input, change.pattern, pos, plain)
30 if start and (start < bestStart) then
31 bestStart = start
32 bestStop = stop
33 bestChange = change
34 end
35 end
36 result = result .. mw.ustring.sub(input, pos, bestStart - 1)
37 if bestChange then
38 local fragment = mw.ustring.sub(input, bestStart, bestStop)
39 result = result .. (plain and bestChange.repl or
40 mw.ustring.gsub(fragment, bestChange.pattern, bestChange.repl, 1))
41 end
42 pos = bestStop + 1
43 end
44 return result
45 end
46
47 function p.main(frame, ...)
48 local args =
49 type(frame) ~= 'table' and {frame, ...} or
50 type(frame.args) ~= 'table' and frame or
51 frame.args[1] and frame.args or
52 frame:getParent().args
53 return MultiReplace(args)
54 end
55
56 return p