Module:String

--

This module is intended to provide access to basic string functions.

Most of the functions provided here can be invoked with named parameters,

unnamed parameters, or a mixture. If named parameters are used, Mediawiki will

automatically remove any leading or trailing whitespace from the parameter.

Depending on the intended use, it may be advantageous to either preserve or

remove such whitespace.

Global options

ignore_errors: If set to 'true' or 1, any error condition will result in

an empty string being returned rather than an error message.

error_category: If an error occurs, specifies the name of a category to

include with the error message. The default category is

Category:Errors reported by Module String.

no_category: If set to 'true' or 1, no category will be added if an error

is generated.

Unit tests for this module are available at Module:String/tests.

local str =

--

len

This function returns the length of the target string.

Usage:

OR

Parameters

s: The string whose length to report

If invoked using named parameters, Mediawiki will automatically remove any leading or

trailing whitespace from the target string.

function str.len (frame)

local newargs = str.getParameters (frame.args, {'s'} );

local s = new_args's' or ;

return mw.ustring.len (s)

end

--

sub

This function returns a substring of the target string at specified indices.

Usage:

OR

Parameters

s: The string to return a subset of

i: The fist index of the substring to return, defaults to 1.

j: The last index of the string to return, defaults to the last character.

The first character of the string is assigned an index of 1. If either i or j

is a negative value, it is interpreted the same as selecting a character by

counting from the end of the string. Hence, a value of -1 is the same as

selecting the last character of the string.

If the requested indices are out of range for the given string, an error is

reported.

function str.sub (frame)

local newargs = str.getParameters (frame.args, { 's', 'i', 'j'} );

local s = new_args's' or ;

local i = tonumber (new_args'i') or 1;

local j = tonumber (new_args'j') or -1;

local len = mw.ustring.len (s);

-- Convert negatives for range checking

if i len or j > len or i mw.ustring.len (s) then

return str._error (' 要求的起始點脫離區間 ');

end

if match_index == 0 then

return str._error (' 匹配索引脫離區間 ');

end

if plain_flag then

pattern = str._escapePattern (pattern);

end

local result

if match_index == 1 then

-- Find first match is simple case

result = mw.ustring.match (s, pattern, start)

else

if start > 1 then

s = mw.ustring.sub (s, start);

end

local iterator = mw.ustring.gmatch (s, pattern);

if match_index > 0 then

-- Forward search

for w in iterator do

matchindex = matchindex - 1;

if match_index == 0 then

result = w;

break;

end

end

else

-- Reverse search

local result_table = ;

local count = 1;

for w in iterator do

result_tablecount = w;

count = count + 1;

end

result = resulttable count + matchindex ;

end

end

if result == nil then

if nomatch == nil then

return str._error (' 找不到匹配 ');

else

return nomatch;

end

else

return result;

end

end

--

pos

This function returns a single character from the target string at position pos.

Usage:

OR

Parameters

target: The string to search

pos: The index for the character to return

If invoked using named parameters, Mediawiki will automatically remove any leading or

trailing whitespace from the target string. In some circumstances this is desirable, in

other cases one may want to preserve the whitespace.

The first character has an index value of 1.

If one requests a negative value, this function will select a character by counting backwards

from the end of the string. In other words pos = -1 is the same as asking for the last character.

A requested value of zero, or a value greater than the length of the string returns an error.

function str.pos (frame)

local newargs = str.getParameters (frame.args, {'target', 'pos'} );

local targetstr = newargs'target' or ;

local pos = tonumber (new_args'pos') or 0;

if pos == 0 or math.abs (pos) > mw.ustring.len (target_str) then

return str._error (' 字串索引脫離區間 ');

end

return mw.ustring.sub (target_str, pos, pos);

end

--

str_find

This function duplicates the behavior of , including all of its quirks.

This is provided in order to support existing templates, but is NOT RECOMMENDED for

new code and templates. New code is recommended to use the "find" function instead.

Returns the first index in "source" that is a match to "target". Indexing is 1-based,

and the function returns -1 if the "target" string is not present in "source".

Important Note: If the "target" string is empty /missing, this function returns a

value of "1", which is generally unexpected behavior, and must be accounted for

separatetly.

function str.str_find (frame)

local newargs = str.getParameters (frame.args, {'source', 'target'} );

local sourcestr = newargs'source' or ;

local targetstr = newargs'target' or ;

if target_str == then

return 1;

end

local start = mw.ustring.find (sourcestr, targetstr, 1, true)

if start == nil then

start = -1

end

return start

end

--

find

This function allows one to search for a target string or pattern within another

string.

Usage:

OR

Parameters

source: The string to search

target: The string or pattern to find within source

start: The index within the source string to start the search, defaults to 1

plain: Boolean flag indicating that target should be understood as plain

text and not as a Lua style regular expression, defaults to true

If invoked using named parameters, Mediawiki will automatically remove any leading or

trailing whitespace from the parameter. In some circumstances this is desirable, in

other cases one may want to preserve the whitespace.

This function returns the first index >= "start" where "target" can be found

within "source". Indices are 1-based. If "target" is not found, then this

function returns 0. If either "source" or "target" are missing /empty, this

function also returns 0.

This function should be safe for UTF-8 strings.

function str.find (frame)

local newargs = str.getParameters (frame.args, {'source', 'target', 'start', 'plain'} );

local sourcestr = newargs'source' or ;

local pattern = new_args'target' or ;

local startpos = tonumber (newargs'start') or 1;

local plain = new_args'plain' or true;

if source_str == or pattern == then

return 0;

end

plain = str._getBoolean (plain);

local start = mw.ustring.find (sourcestr, pattern, startpos, plain)

if start == nil then

start = 0

end

return start

end

--

replace

This function allows one to replace a target string or pattern within another

string.

Usage:

OR

Parameters

source: The string to search

pattern: The string or pattern to find within source

replace: The replacement text

count: The number of occurences to replace, defaults to all.

plain: Boolean flag indicating that pattern should be understood as plain

text and not as a Lua style regular expression, defaults to true

function str.replace (frame)

local newargs = str.getParameters (frame.args, {'source', 'pattern', 'replace', 'count', 'plain'} );

local sourcestr = newargs'source' or ;

local pattern = new_args'pattern' or ;

local replace = new_args'replace' or ;

local count = tonumber (new_args'count');

local plain = new_args'plain' or true;

if source_str == or pattern == then

return source_str;

end

plain = str._getBoolean (plain);

if plain then

pattern = str._escapePattern (pattern);

replace = mw.ustring.gsub (replace, "%%", "%%%%"); --Only need to escape replacement sequences.

end

local result;

if count ~= nil then

result = mw.ustring.gsub (source_str, pattern, replace, count);

else

result = mw.ustring.gsub (source_str, pattern, replace);

end

return result;

end

--

simple function to pipe string.rep to templates.

function str.rep (frame)

local repetitions = tonumber (frame.args2)

if not repetitions then

return str._error ('function rep expects a number as second parameter, received "' .. ( frame.args2 or) .. '"' )

end

return string.rep (frame.args1 or , repetitions)

end

function str.split (inputstr, sep, nopattern, ignorenull)

	--#invoke 支援

	if type (inputstr) == type ({table}) then

		if not getArgs then getArgs = require ('Module:Arguments').getArgs end

		args = getArgs (inputstr, {parentFirst=true})

		for argname, argvalue in pairs (args) do

			if argname == 1 or argname == '1' or argname == "str" or argname == "inputstr" or arg_name == "input" then

				inputstr = argvalue

			elseif argname == 2 or argname == '2' or argname == "sep" or argname == "separator" then

				separ = arg_value

			elseif argname == 3 or argname == '3' or argname == "nopattern" or arg_name == "no pattern" then

				nopatternflag = arg_value

			elseif argname == 4 or argname == '4' or argname == "ignorenull" or arg_name == "ignore null" then

				ignorenullflag = arg_value

			elseif argname == 5 or argname == '5' or arg_name == "format" then

				format = arg_value or "*}\n";

			end

		end

		if not yesno then yesno = require ('Module:Yesno') end

		nopatternflag = yesno (nopatternflag or 'yes')

		ignorenullflag = yesno (ignorenullflag or 'no')

		is_invoke = true

		format = mw.ustring.gsub (format or "*}\n", "%{%{%{.-%}%}%}", "%% s" );

		it = mw.ustring.find (format, "%% s", 1)

		if it == nil then format = format .. "% s" end

		format = mw.ustring.gsub (format, "\\n", "\n")

	else

		input_str = inputstr

		separ = sep

		nopatternflag = no_pattern

		ignorenullflag = ignore_null

		is_invoke = false

	end

	inputstr = inputstr or

	separ = separ or "% s"

	if nopatternflag == nil then nopatternflag = true end

	if ignorenullflag == nil then ignorenullflag = false end

	length = mw.ustring.len (input_str)

	--split 函式起點

	if nopatternflag then

		separ = mw.ustring.gsub (mw.ustring.gsub (mw.ustring.gsub (mw.ustring.gsub (mw.ustring.gsub (mw.ustring.gsub (mw.ustring.gsub (mw.ustring.gsub (mw.ustring.gsub (mw.ustring.gsub (mw.ustring.gsub (mw.ustring.gsub (mw.ustring.gsub (mw.ustring.gsub (separ,

			"%", "%"), "%", "%"), "%{", "%{"), "%}", "%}"), "%%", "%%%%"), "%)", "%)"), "%-", "%-"),

			"%^", "%^"), "%$", "%$"), "%(", "%("), "%.", "%."), "%", "%"), "%+", "%+"), "%|", "%|");

	end

	iterator = 1 ; i = 1 ; flag = true

	result =

	separstrbegin, separstrend = mw.ustring.find (input_str, separ, iterator)

	--

	debug1 = 1

	--

	while flag do

		debug1 = debug1 + 1

		if separstrbegin == nil or iterator > length or debug1 >= 100 then

			separstrbegin = 0

			separstrend = -2

			flag = false

		end

		if separstrend 字串模組出錯：' .. error_str .. ;

if errorcategory ~= and not str.getBoolean (no_category) then

errorstr = .. errorstr;

end

return error_str;

end

--

Helper Function to interpret boolean strings

function str.getBoolean (booleanstr)

local boolean_value;

if type (boolean_str) == 'string' then

booleanstr = booleanstr:lower ;

if booleanstr == 'false' or booleanstr == 'no' or boolean_str == '0'

or boolean_str == then

boolean_value = false;

else

boolean_value = true;

end

elseif type (boolean_str) == 'boolean' then

booleanvalue = booleanstr;

else

error (' 布林值找不到 ');

end

return boolean_value

end

--

Helper function that escapes all pattern characters so that they will be treated

as plain text.

function str.escapePattern (patternstr)

return mw.ustring.gsub (pattern_str, "(%(%)%.%%%+%-%*%?%%^%$%)", "%%%1" );

end

return str