Modul:String

Technology
12 hours ago
8
4
2
Avatar
Author
Albert Flores

--[[

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. +more 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 = {}

--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. '> 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. +morelen( frame ) local new_args = str. _getParameters( frame. args, {'s'} ) local s = new_args['s'] or return mw. ustring. len( s ) end.

--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. +more_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. '> 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. +more 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. +moresub( frame ) local new_args = 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 1 then s = mw.ustring.sub( s, start ) end

local iterator = mw. ustring. +moregmatch(s, pattern) if match_index > 0 then -- Forward search for w in iterator do match_index = match_index - 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_table[count] = w count = count + 1 end.

result = result_table[ count + match_index ] end end

if result

nil then if nomatch

nil then return str. _error( 'Match not found' ) else return nomatch end else return result end end -- This is the entry point for #invoke:String|match function str. +morematch( frame ) local new_args = str. _getParameters( frame. args, {'s', 'pattern', 'start', 'match', 'plain', 'nomatch'} ) local s = new_args['s'] or local start = tonumber( new_args['start'] ) or 1 local plain_flag = str. _getBoolean( new_args['plain'] or false ) local pattern = new_args['pattern'] or local match_index = math. floor( tonumber(new_args['match']) or 1 ) local nomatch = new_args['nomatch'].

return str._match( s, pattern, start, match_index, plain_flag, nomatch ) end

--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. '> 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. +morepos( frame ) local new_args = str. _getParameters( frame. args, {'target', 'pos'} ) local target_str = new_args['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( 'String index out of range' ) end

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

-- 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. +more_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. '> 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. +more 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. +morestr_find( frame ) local new_args = str. _getParameters( frame. args, {'source', 'target'} ) local source_str = new_args['source'] or local target_str = new_args['target'] or.

if target_str == then return 1 end

local start = mw.ustring.find( source_str, target_str, 1, true ) if start == nil then start = -1 end

return start end

--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. +more_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. '> 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. +more 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. +morefind( frame ) local new_args = str. _getParameters( frame. args, {'source', 'target', 'start', 'plain' } ) local source_str = new_args['source'] or local pattern = new_args['target'] or local start_pos = tonumber(new_args['start']) or 1 local plain = new_args['plain'] or true.

if source_str

Important

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

--[url=://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#Patterns

Usage:

Parameters pattern_string: The pattern string to escape. ][ simple function to pipe string. +morerep to templates. ]] function str. rep( frame ) local repetitions = tonumber( frame. args[2] ) if not repetitions then return str. _error( 'function rep expects a number as second parameter, received "' . ( frame. args[2] or ) . '"' ) end return string. rep( frame. args[1] or , repetitions ) end.

--[[ escapePattern

This function escapes special characters from a Lua string pattern. See [1] for details on how patterns work.

[1][/url]] function str. escapePattern( frame ) local pattern_str = frame. +moreargs[1] if not pattern_str then return str. _error( 'No pattern string specified' ) end local result = str. _escapePattern( pattern_str ) return result end.

-- count This function counts the number of occurrences of one string in another. +more function str. count(frame) local args = str. _getParameters(frame. args, {'source', 'pattern', 'plain'}) local source = args. source or local pattern = args. pattern or local plain = str. _getBoolean(args. plain or true) if plain then pattern = str. _escapePattern(pattern) end local _, count = mw. ustring. gsub(source, pattern) return count end.

-- endswith This function determines whether a string ends with another string. +more function str. endswith(frame) local args = str. _getParameters(frame. args, {'source', 'pattern'}) local source = args. source or local pattern = args. pattern or if pattern.

then -- All strings end with the empty string. return "yes" end if mw.ustring.sub(source, -mw.ustring.len(pattern), -1)

pattern then return "yes" else return "" end end

--Join_all_non_empty_arguments_together;_the_first_argument_is_the_separator. Usage:

'> join

Join all non empty arguments together; the first argument is the separator. Usage:

function str. join(frame) local args = {} local sep for _, v in ipairs( frame. +moreargs ) do if sep then if v ~= then table. insert(args, v) end else sep = v end end return table. concat( args, sep or ) end.

--+more '> Helper function that populates the argument list given that user may need to use a mix of named and unnamed parameters. This is relevant because named parameters are not identical to unnamed parameters due to string trimming, and when dealing with strings we sometimes want to either preserve or remove that whitespace depending on the application. function str. _getParameters( frame_args, arg_list ) local new_args = {} local index = 1 local value.

for _, arg in ipairs( arg_list ) do value = frame_args[arg] if value == nil then value = frame_args[index] index = index + 1 end new_args[arg] = value end

return new_args end

-- Helper function to handle error messages. +more function str. _error( error_str ) local frame = mw. getCurrentFrame local error_category = frame. args. error_category or 'Údržba:Chyby hlášené Modulem String' local ignore_errors = frame. args. ignore_errors or false local no_category = frame. args. no_category or false.

if str._getBoolean(ignore_errors) then return end

local error_str = 'String Module Error: ' .. error_str .. '' if error_category ~= and not str._getBoolean( no_category ) then error_str = '[[Category:' .. error_category .. ']]' .. error_str end

return error_str 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' or boolean_str

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. +more function str. _escapePattern( pattern_str ) return mw. ustring. gsub( pattern_str, "([%(%)%. %%%+%-%*%. %[%^%$%]])", "%%%1" ) end.

-- Helper function that listifies lines of input text. +more function str. listifyLines(text) local result = {} for idx,line in ipairs(mw. text. split(text, "\n", true)) do if line ~= "" then table. insert(result, "* " . line) end end local list = table. concat(result, "\n") return list end.

-- Helper function that delistifies lines of input text. +more function str. delistifyLines(text) local result = {} for idx,line in ipairs(mw. text. split(text, "\n", true)) do if line ~= "" then table. insert(result, tostring(line:gsub("^[*#]+ *", ""))) end end local lines = table. concat(result, "\n") return lines end.

--This_function_listifies_lines_of_input_text.

Usage:

Parameters 1:_The_string_which_will_be_listified '> listify

This function listifies lines of input text.

Usage:

Parameters 1: The string which will be listified function str.listify(frame) return str.listifyLines(frame.args[1]) end

--This_function_delistifies_lines_of_input_text.

Usage:

Parameters 1:_The_string_which_will_be_delistified '> delistify

This function delistifies lines of input text.

Usage:

Parameters 1: The string which will be delistified function str.delistify(frame) return str.delistifyLines(frame.args[1]) end

return str

5 min read
Share this post:
Like it 8

Leave a Comment

Please, enter your name.
Please, provide a valid email address.
Please, enter your comment.
Enjoy this post? Join Cesko.wiki
Don’t forget to share it
Top