Documentation for this module may be created at Module:String/doc

  1. --[[
  2.  
  3. This module is intended to provide access to basic string functions.
  4.  
  5. Most of the functions provided here can be invoked with named parameters,
  6. unnamed parameters, or a mixture. If named parameters are used, Mediawiki will
  7. automatically remove any leading or trailing whitespace from the parameter.
  8. Depending on the intended use, it may be advantageous to either preserve or
  9. remove such whitespace.
  10.  
  11. Global options
  12. ignore_errors: If set to 'true' or 1, any error condition will result in
  13. an empty string being returned rather than an error message.
  14. error_category: If an error occurs, specifies the name of a category to
  15. include with the error message. The default category is
  16. [Category:Errors reported by Module String].
  17. no_category: If set to 'true' or 1, no category will be added if an error
  18. is generated.
  19. Unit tests for this module are available at Module:String/tests.
  20. ]]
  21.  
  22. local str = {}
  23.  
  24. --[[
  25. len
  26.  
  27. This function returns the length of the target string.
  28.  
  29. Usage:
  30. {{#invoke:String|len|target_string|}}
  31. OR
  32. {{#invoke:String|len|s=target_string}}
  33.  
  34. Parameters
  35. s: The string whose length to report
  36.  
  37. If invoked using named parameters, Mediawiki will automatically remove any leading or
  38. trailing whitespace from the target string.
  39. ]]
  40. function str.len( frame )
  41. local new_args = str._getParameters( frame.args, {'s'} );
  42. local s = new_args['s'] or '';
  43. return mw.ustring.len( s )
  44. end
  45.  
  46. --[[
  47. sub
  48.  
  49. This function returns a substring of the target string at specified indices.
  50.  
  51. Usage:
  52. {{#invoke:String|sub|target_string|start_index|end_index}}
  53. OR
  54. {{#invoke:String|sub|s=target_string|i=start_index|j=end_index}}
  55.  
  56. Parameters
  57. s: The string to return a subset of
  58. i: The fist index of the substring to return, defaults to 1.
  59. j: The last index of the string to return, defaults to the last character.
  60. The first character of the string is assigned an index of 1. If either i or j
  61. is a negative value, it is interpreted the same as selecting a character by
  62. counting from the end of the string. Hence, a value of -1 is the same as
  63. selecting the last character of the string.
  64.  
  65. If the requested indices are out of range for the given string, an error is
  66. reported.
  67. ]]
  68. function str.sub( frame )
  69. local new_args = str._getParameters( frame.args, { 's', 'i', 'j' } );
  70. local s = new_args['s'] or '';
  71. local i = tonumber( new_args['i'] ) or 1;
  72. local j = tonumber( new_args['j'] ) or -1;
  73. local len = mw.ustring.len( s );
  74.  
  75. -- Convert negatives for range checking
  76. if i < 0 then
  77. i = len + i + 1;
  78. end
  79. if j < 0 then
  80. j = len + j + 1;
  81. end
  82. if i > len or j > len or i < 1 or j < 1 then
  83. return str._error( 'String subset index out of range' );
  84. end
  85. if j < i then
  86. return str._error( 'String subset indices out of order' );
  87. end
  88. return mw.ustring.sub( s, i, j )
  89. end
  90.  
  91. --[[
  92. This function implements that features of {{str sub old}} and is kept in order
  93. to maintain these older templates.
  94. ]]
  95. function str.sublength( frame )
  96. local i = tonumber( frame.args.i ) or 0
  97. local len = tonumber( frame.args.len )
  98. return mw.ustring.sub( frame.args.s, i + 1, len and ( i + len ) )
  99. end
  100.  
  101. --[[
  102. match
  103.  
  104. This function returns a substring from the source string that matches a
  105. specified pattern.
  106.  
  107. Usage:
  108. {{#invoke:String|match|source_string|pattern_string|start_index|match_number|plain_flag|nomatch_output}}
  109. OR
  110. {{#invoke:String|pos|s=source_string|pattern=pattern_string|start=start_index
  111. |match=match_number|plain=plain_flag|nomatch=nomatch_output}}
  112.  
  113. Parameters
  114. s: The string to search
  115. pattern: The pattern or string to find within the string
  116. start: The index within the source string to start the search. The first
  117. character of the string has index 1. Defaults to 1.
  118. match: In some cases it may be possible to make multiple matches on a single
  119. string. This specifies which match to return, where the first match is
  120. match= 1. If a negative number is specified then a match is returned
  121. counting from the last match. Hence match = -1 is the same as requesting
  122. the last match. Defaults to 1.
  123. plain: A flag indicating that the pattern should be understood as plain
  124. text. Defaults to false.
  125. nomatch: If no match is found, output the "nomatch" value rather than an error.
  126.  
  127. If invoked using named parameters, Mediawiki will automatically remove any leading or
  128. trailing whitespace from each string. In some circumstances this is desirable, in
  129. other cases one may want to preserve the whitespace.
  130.  
  131. If the match_number or start_index are out of range for the string being queried, then
  132. this function generates an error. An error is also generated if no match is found.
  133. If one adds the parameter ignore_errors=true, then the error will be suppressed and
  134. an empty string will be returned on any failure.
  135.  
  136. For information on constructing Lua patterns, a form of [regular expression], see:
  137.  
  138. * http://www.lua.org/manual/5.1/manual.html#5.4.1
  139. * http://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#Patterns
  140. * http://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#Ustring_patterns
  141.  
  142. ]]
  143. function str.match( frame )
  144. local new_args = str._getParameters( frame.args, {'s', 'pattern', 'start', 'match', 'plain', 'nomatch'} );
  145. local s = new_args['s'] or '';
  146. local start = tonumber( new_args['start'] ) or 1;
  147. local plain_flag = str._getBoolean( new_args['plain'] or false );
  148. local pattern = new_args['pattern'] or '';
  149. local match_index = math.floor( tonumber(new_args['match']) or 1 );
  150. local nomatch = new_args['nomatch'];
  151. if s == '' then
  152. return str._error( 'Target string is empty' );
  153. end
  154. if pattern == '' then
  155. return str._error( 'Pattern string is empty' );
  156. end
  157. if math.abs(start) < 1 or math.abs(start) > mw.ustring.len( s ) then
  158. return str._error( 'Requested start is out of range' );
  159. end
  160. if match_index == 0 then
  161. return str._error( 'Match index is out of range' );
  162. end
  163. if plain_flag then
  164. pattern = str._escapePattern( pattern );
  165. end
  166. local result
  167. if match_index == 1 then
  168. -- Find first match is simple case
  169. result = mw.ustring.match( s, pattern, start )
  170. else
  171. if start > 1 then
  172. s = mw.ustring.sub( s, start );
  173. end
  174. local iterator = mw.ustring.gmatch(s, pattern);
  175. if match_index > 0 then
  176. -- Forward search
  177. for w in iterator do
  178. match_index = match_index - 1;
  179. if match_index == 0 then
  180. result = w;
  181. break;
  182. end
  183. end
  184. else
  185. -- Reverse search
  186. local result_table = {};
  187. local count = 1;
  188. for w in iterator do
  189. result_table[count] = w;
  190. count = count + 1;
  191. end
  192. result = result_table[ count + match_index ];
  193. end
  194. end
  195. if result == nil then
  196. if nomatch == nil then
  197. return str._error( 'Match not found' );
  198. else
  199. return nomatch;
  200. end
  201. else
  202. return result;
  203. end
  204. end
  205.  
  206. --[[
  207. pos
  208.  
  209. This function returns a single character from the target string at position pos.
  210.  
  211. Usage:
  212. {{#invoke:String|pos|target_string|index_value}}
  213. OR
  214. {{#invoke:String|pos|target=target_string|pos=index_value}}
  215.  
  216. Parameters
  217. target: The string to search
  218. pos: The index for the character to return
  219.  
  220. If invoked using named parameters, Mediawiki will automatically remove any leading or
  221. trailing whitespace from the target string. In some circumstances this is desirable, in
  222. other cases one may want to preserve the whitespace.
  223.  
  224. The first character has an index value of 1.
  225.  
  226. If one requests a negative value, this function will select a character by counting backwards
  227. from the end of the string. In other words pos = -1 is the same as asking for the last character.
  228.  
  229. A requested value of zero, or a value greater than the length of the string returns an error.
  230. ]]
  231. function str.pos( frame )
  232. local new_args = str._getParameters( frame.args, {'target', 'pos'} );
  233. local target_str = new_args['target'] or '';
  234. local pos = tonumber( new_args['pos'] ) or 0;
  235.  
  236. if pos == 0 or math.abs(pos) > mw.ustring.len( target_str ) then
  237. return str._error( 'String index out of range' );
  238. end
  239. return mw.ustring.sub( target_str, pos, pos );
  240. end
  241.  
  242. --[[
  243. str_find
  244.  
  245. This function duplicates the behavior of {{str_find}}, including all of its quirks.
  246. This is provided in order to support existing templates, but is NOT RECOMMENDED for
  247. new code and templates. New code is recommended to use the "find" function instead.
  248.  
  249. Returns the first index in "source" that is a match to "target". Indexing is 1-based,
  250. and the function returns -1 if the "target" string is not present in "source".
  251.  
  252. Important Note: If the "target" string is empty / missing, this function returns a
  253. value of "1", which is generally unexpected behavior, and must be accounted for
  254. separatetly.
  255. ]]
  256. function str.str_find( frame )
  257. local new_args = str._getParameters( frame.args, {'source', 'target'} );
  258. local source_str = new_args['source'] or '';
  259. local target_str = new_args['target'] or '';
  260.  
  261. if target_str == '' then
  262. return 1;
  263. end
  264. local start = mw.ustring.find( source_str, target_str, 1, true )
  265. if start == nil then
  266. start = -1
  267. end
  268. return start
  269. end
  270.  
  271. --[[
  272. find
  273.  
  274. This function allows one to search for a target string or pattern within another
  275. string.
  276.  
  277. Usage:
  278. {{#invoke:String|find|source_str|target_string|start_index|plain_flag}}
  279. OR
  280. {{#invoke:String|find|source=source_str|target=target_str|start=start_index|plain=plain_flag}}
  281.  
  282. Parameters
  283. source: The string to search
  284. target: The string or pattern to find within source
  285. start: The index within the source string to start the search, defaults to 1
  286. plain: Boolean flag indicating that target should be understood as plain
  287. text and not as a Lua style regular expression, defaults to true
  288.  
  289. If invoked using named parameters, Mediawiki will automatically remove any leading or
  290. trailing whitespace from the parameter. In some circumstances this is desirable, in
  291. other cases one may want to preserve the whitespace.
  292.  
  293. This function returns the first index >= "start" where "target" can be found
  294. within "source". Indices are 1-based. If "target" is not found, then this
  295. function returns 0. If either "source" or "target" are missing / empty, this
  296. function also returns 0.
  297.  
  298. This function should be safe for UTF-8 strings.
  299. ]]
  300. function str.find( frame )
  301. local new_args = str._getParameters( frame.args, {'source', 'target', 'start', 'plain' } );
  302. local source_str = new_args['source'] or '';
  303. local pattern = new_args['target'] or '';
  304. local start_pos = tonumber(new_args['start']) or 1;
  305. local plain = new_args['plain'] or true;
  306. if source_str == '' or pattern == '' then
  307. return 0;
  308. end
  309. plain = str._getBoolean( plain );
  310.  
  311. local start = mw.ustring.find( source_str, pattern, start_pos, plain )
  312. if start == nil then
  313. start = 0
  314. end
  315. return start
  316. end
  317.  
  318. --[[
  319. replace
  320.  
  321. This function allows one to replace a target string or pattern within another
  322. string.
  323.  
  324. Usage:
  325. {{#invoke:String|replace|source_str|pattern_string|replace_string|replacement_count|plain_flag}}
  326. OR
  327. {{#invoke:String|replace|source=source_string|pattern=pattern_string|replace=replace_string|
  328. count=replacement_count|plain=plain_flag}}
  329.  
  330. Parameters
  331. source: The string to search
  332. pattern: The string or pattern to find within source
  333. replace: The replacement text
  334. count: The number of occurences to replace, defaults to all.
  335. plain: Boolean flag indicating that pattern should be understood as plain
  336. text and not as a Lua style regular expression, defaults to true
  337. ]]
  338. function str.replace( frame )
  339. local new_args = str._getParameters( frame.args, {'source', 'pattern', 'replace', 'count', 'plain' } );
  340. local source_str = new_args['source'] or '';
  341. local pattern = new_args['pattern'] or '';
  342. local replace = new_args['replace'] or '';
  343. local count = tonumber( new_args['count'] );
  344. local plain = new_args['plain'] or true;
  345. if source_str == '' or pattern == '' then
  346. return source_str;
  347. end
  348. plain = str._getBoolean( plain );
  349.  
  350. if plain then
  351. pattern = str._escapePattern( pattern );
  352. replace = mw.ustring.gsub( replace, "%%", "%%%%" ); --Only need to escape replacement sequences.
  353. end
  354. local result;
  355.  
  356. if count ~= nil then
  357. result = mw.ustring.gsub( source_str, pattern, replace, count );
  358. else
  359. result = mw.ustring.gsub( source_str, pattern, replace );
  360. end
  361.  
  362. return result;
  363. end
  364.  
  365. --[[
  366. simple function to pipe string.rep to templates.
  367. ]]
  368.  
  369. function str.rep( frame )
  370. local repetitions = tonumber( frame.args[2] )
  371. if not repetitions then
  372. return str._error( 'function rep expects a number as second parameter, received "' .. ( frame.args[2] or '' ) .. '"' )
  373. end
  374. return string.rep( frame.args[1] or '', repetitions )
  375. end
  376.  
  377. --[[
  378. Helper function that populates the argument list given that user may need to use a mix of
  379. named and unnamed parameters. This is relevant because named parameters are not
  380. identical to unnamed parameters due to string trimming, and when dealing with strings
  381. we sometimes want to either preserve or remove that whitespace depending on the application.
  382. ]]
  383. function str._getParameters( frame_args, arg_list )
  384. local new_args = {};
  385. local index = 1;
  386. local value;
  387. for i,arg in ipairs( arg_list ) do
  388. value = frame_args[arg]
  389. if value == nil then
  390. value = frame_args[index];
  391. index = index + 1;
  392. end
  393. new_args[arg] = value;
  394. end
  395. return new_args;
  396. end
  397.  
  398. --[[
  399. Helper function to handle error messages.
  400. ]]
  401. function str._error( error_str )
  402. local frame = mw.getCurrentFrame();
  403. local error_category = frame.args.error_category or 'Errors reported by Module String';
  404. local ignore_errors = frame.args.ignore_errors or false;
  405. local no_category = frame.args.no_category or false;
  406. if str._getBoolean(ignore_errors) then
  407. return '';
  408. end
  409. local error_str = '<strong class="error">String Module Error: ' .. error_str .. '</strong>';
  410. if error_category ~= '' and not str._getBoolean( no_category ) then
  411. error_str = '[[Category:' .. error_category .. ']]' .. error_str;
  412. end
  413. return error_str;
  414. end
  415.  
  416. --[[
  417. Helper Function to interpret boolean strings
  418. ]]
  419. function str._getBoolean( boolean_str )
  420. local boolean_value;
  421. if type( boolean_str ) == 'string' then
  422. boolean_str = boolean_str:lower();
  423. if boolean_str == 'false' or boolean_str == 'no' or boolean_str == '0'
  424. or boolean_str == '' then
  425. boolean_value = false;
  426. else
  427. boolean_value = true;
  428. end
  429. elseif type( boolean_str ) == 'boolean' then
  430. boolean_value = boolean_str;
  431. else
  432. error( 'No boolean value found' );
  433. end
  434. return boolean_value
  435. end
  436.  
  437. --[[
  438. Helper function that escapes all pattern characters so that they will be treated
  439. as plain text.
  440. ]]
  441. function str._escapePattern( pattern_str )
  442. return mw.ustring.gsub( pattern_str, "([%(%)%.%%%+%-%*%?%[%^%$%]])", "%%%1" );
  443. end
  444.  
  445. return str