Jump to content
Wikipedia The Free Encyclopedia

Module:MultiReplace

From Wikipedia, the free encyclopedia
Module documentation[view] [edit] [history] [purge]
Warning This Lua module is used on approximately 1,470,000 pages, or roughly 2% of all pages .
To avoid major disruption and server load, any changes should be tested in the module's /sandbox or /testcases subpages, or in your own module sandbox. The tested changes can be added to this page in a single edit. Consider discussing changes on the talk page before implementing them.
This module depends on the following other modules:
For a function to search for multiple patterns, see {{#invoke:string2|matchAny}}. For a function to replace multiple parameters at once, see {{#invoke:params|mapping_by_replacing}}.

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.

An equals sign in a pattern will trigger an Unpaired argument error. Use {{=}}, which expands to an equals sign that will not be interpreted.

The above documentation is transcluded from Module:MultiReplace/doc. (edit | history)
Editors can experiment in this module's sandbox (edit | diff) and testcases (create) pages.
Subpages of this module.

 localp={}

 localfunctionMultiReplace(args)
 localinput=args[1]or"{{{1}}}"
 localplain=args.plain=="yes"

 locali=1
 localchangeList={}
 whileargs[i*2]do
 localchange={pattern=args[i*2],repl=args[i*2+1]}
 ifnotchange.replthen
 returnrequire('Module:Error').error{
 'MultiReplace: Unpaired argument: <code>'..(i*2)..' = '..mw.text.nowiki(change.pattern)..'</code>'
 }
 end
 changeList[i]=change
 i=i+1
 end

 localmatchList={}
 localpos=1
 locallen=mw.ustring.len(input)
 localresult=""
 whilepos<=lendo
 localbestStart=len+1
 localbestStop=len
 localbestChange
 for_,changeinipairs(changeList)do
 localstart,stop=mw.ustring.find(input,change.pattern,pos,plain)
 ifstartand(start<bestStart)then
 bestStart=start
 bestStop=stop
 bestChange=change
 end
 end
 result=result..mw.ustring.sub(input,pos,bestStart-1)
 ifbestChangethen
 localfragment=mw.ustring.sub(input,bestStart,bestStop)
 result=result..(plainandbestChange.replor
 mw.ustring.gsub(fragment,bestChange.pattern,bestChange.repl,1))
 end
 pos=bestStop+1
 end
 returnresult
 end

 functionp.main(frame,...)
 localargs=
 type(frame)~='table'and{frame,...}or
 type(frame.args)~='table'andframeor
 frame.args[1]andframe.argsor
 frame:getParent().args
 returnMultiReplace(args)
 end

 returnp

AltStyle によって変換されたページ (->オリジナル) /