Changes

Jump to: navigation, search

Module:String

773 bytes added, 12:31, 24 February 2013
include more generic replacement function
end
if type( plain ) == 'string' then str._getBoolean( plain = plain:lower(); if plain == 'false' or plain == 'no' or plain == '0' then plain = false; else plain = true; end end
local start = mw.ustring.find( source_str, pattern, start_pos, plain )
--[====[
replace_plainreplace
This function allows one to replace a target string or pattern within another
Usage:
{{#invoke:String|replace_plain|source_str|pattern_string|replace_string|firstonlyflagreplacement_count|pattern_flag}}
OR
{{#invoke:String|replace_plain|source=source_str|pattern=pattern_str|replace=replace_string|firstonly count=firstonlyflagreplacement_count|plain=pattern_flag}}
Parameters
source: The string to search
pattenpattern: The string or pattern to find within source
replace: The replacement text
firstonlycount: The number of occurences to replace, defaults to all. plain: Boolean flag indicating that only the first occurence found pattern should be replacedunderstood as plain text and not as a Lua style regular expression, defaults to true
]====]
function str.replace_plainreplace( frame ) local new_args = str._getParameters( frame.args, {'source', 'pattern', 'replace', 'firstonlycount', 'plain' } );
local source_str = new_args['source'] or '';
local pattern = new_args['pattern'] or '';
local replace = new_args['replace'] or '';
local firstonly count = tonumber( new_args['firstonlycount'] or ''); firstonly local plain = firstonly:lower()new_args['plain'] or true;
if source_str == '' or pattern == '' then
return source_str;
end
plain = str._getBoolean( plain );
local pattern_plain if plain then pattern = mwstr.ustring.gsub_escapePattern(pattern, '%%', '%%%%'); local replace_plain replace = mw.ustringstr.gsub_escapePattern(replace, '%%', '%%%%'); end
local result;
if firstonly count ~== 'true' or firstonly == 'yes' or firstonly == '1' nil then result = mw.ustring.gsub( source_str, pattern_plainpattern, replace_plainreplace, 1 count );
else
result = mw.ustring.gsub( source_str, pattern_plainpattern, replace_plain, n replace ); end
return result;
return new_args;
end
 
--[====[
Helper Function to interpret boolean strings
]====]
function str._getBoolean( boolean_str )
local boolean_value;
if type( boolean_str ) == 'string' then
boolean_str = boolean_str:lower();
if boolean_str == 'false' or boolean_str == 'no' or boolean_str == '0' then
boolean_value = false;
else
boolean_value = true;
end
elseif type( boolean_str ) == 'boolean' then
boolean_value = boolean_str;
else
error( 'No boolean value found' );
end
return boolean_value
end
 
--[====[
Helper function that escapes all pattern characters so that they will be treated
as plain text.
]====]
function str._escapePattern( pattern_str )
return mw.ustring.gsub( pattern_str, "([%(%)%.%%%+%-%*%?%[%^%$%]])", "%%%1" );
end
return str
Anonymous user

Navigation menu