模块:String

来自萌娘共享
跳转至: 导航搜索

此模块的文档可以在模块:String/doc创建

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