置顶公告:【置顶】关于临时开启评论区所有功能的公告(2022.10.22) | 【置顶】关于本站Widget恢复使用的公告
  • 你好~!欢迎来到萌娘百科镜像站!如需查看或编辑,请联系本站管理员注册账号。
  • 本镜像站和其他萌娘百科的镜像站无关,请注意分别。

Module:String

猛汉♂百科,万男皆可猛的百科全书!转载请标注来源页面的网页链接,并声明引自猛汉百科。内容不可商用。
跳到导航 跳到搜索
Template-info.svg 模块文档  [创建] [刷新]
  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. re_errors:如果设置为'true'或1,则会导致任何错误情况符串而不是错误消息。
  27. r_category:如果发生错误,请指定要分类的名称消息。 默认分类是 [Category:Errors reported by Module String]。(类别:模块字符串报告的错误)
  28. no_category:如果设置为'true'或1,如果发生错误,则不会添加任何分类 生成。
  29. 这个模块的测试单元可以在Module:String / tests下找到。
  30. ]]
  31. local str = {}
  32. --[[
  33. len
  34. This function returns the length of the target string.
  35. Usage:
  36. {{#invoke:String|len|target_string|}}
  37. OR
  38. {{#invoke:String|len|s=target_string}}
  39. Parameters
  40. s: The string whose length to report
  41. If invoked using named parameters, Mediawiki will automatically remove any leading or
  42. trailing whitespace from the target string.
  43. ----
  44. LEN
  45. 该函数返回目标字符串的长度。
  46. 用法:
  47. {{#invoke:String|len|target_string|}}
  48. 要么
  49. {{#invoke:String|len|s=target_string}}
  50. 参数
  51. s:要报告的字符串长度
  52. 如果使用命名参数调用,媒体维基将自动删除任何前部或
  53. 后部目标字符串的空格。
  54. ]]
  55. function str.len( frame )
  56. local new_args = str._getParameters( frame.args, {'s'} );
  57. local s = new_args['s'] or '';
  58. return mw.ustring.len( s )
  59. end
  60. --[[
  61. sub
  62. This function returns a substring of the target string at specified indices.
  63. Usage:
  64. {{#invoke:String|sub|target_string|start_index|end_index}}
  65. OR
  66. {{#invoke:String|sub|s=target_string|i=start_index|j=end_index}}
  67. Parameters
  68. s: The string to return a subset of
  69. i: The fist index of the substring to return, defaults to 1.
  70. j: The last index of the string to return, defaults to the last character.
  71. The first character of the string is assigned an index of 1. If either i or j
  72. is a negative value, it is interpreted the same as selecting a character by
  73. counting from the end of the string. Hence, a value of -1 is the same as
  74. selecting the last character of the string.
  75. If the requested indices are out of range for the given string, an error is
  76. reported.
  77. ----
  78. 該函數返回指定索引處目標字符串的子字符串。
  79. 用法:
  80. {{#invoke:字符串|分| target_string| START_INDEX| END_INDEX}}
  81. 要么
  82. {{#invoke:字符串|子| S= target_string| I= START_INDEX| J = END_INDEX}}
  83. 參數
  84. s:返回一個子集的字符串
  85. i:要返回的子字符串的第一個索引,默認為1。
  86. j:要返回的字符串的最後一個索引,默認為最後一個字符。
  87. 字符串的第一個字符被分配索引1.如果i或j
  88. 是一個負值,它被解釋為與通過選擇一個字符相同
  89. 從字符串的末尾開始計數。 因此,-1的值與1相同
  90. 選擇字符串的最後一個字符。
  91. 如果請求的索引超出給定字符串的範圍,則會出現錯誤
  92. 報導。
  93. ]]
  94. function str.sub( frame )
  95. local new_args = str._getParameters( frame.args, { 's', 'i', 'j' } );
  96. local s = new_args['s'] or '';
  97. local i = tonumber( new_args['i'] ) or 1;
  98. local j = tonumber( new_args['j'] ) or -1;
  99. local len = mw.ustring.len( s );
  100. -- Convert negatives for range checking
  101. if i < 0 then
  102. i = len + i + 1;
  103. end
  104. if j < 0 then
  105. j = len + j + 1;
  106. end
  107. if i > len or j > len or i < 1 or j < 1 then
  108. return str._error( 'String subset index out of range' );
  109. end
  110. if j < i then
  111. return str._error( 'String subset indices out of order' );
  112. end
  113. return mw.ustring.sub( s, i, j )
  114. end
  115. --[[
  116. This function implements that features of {{str sub old}} and is kept in order
  117. to maintain these older templates.
  118. ]]
  119. function str.sublength( frame )
  120. local i = tonumber( frame.args.i ) or 0
  121. local len = tonumber( frame.args.len )
  122. return mw.ustring.sub( frame.args.s, i + 1, len and ( i + len ) )
  123. end
  124. --[[
  125. match
  126. This function returns a substring from the source string that matches a
  127. specified pattern.
  128. Usage:
  129. {{#invoke:String|match|source_string|pattern_string|start_index|match_number|plain_flag|nomatch_output}}
  130. OR
  131. {{#invoke:String|pos|s=source_string|pattern=pattern_string|start=start_index
  132. |match=match_number|plain=plain_flag|nomatch=nomatch_output}}
  133. Parameters
  134. s: The string to search
  135. pattern: The pattern or string to find within the string
  136. start: The index within the source string to start the search. The first
  137. character of the string has index 1. Defaults to 1.
  138. match: In some cases it may be possible to make multiple matches on a single
  139. string. This specifies which match to return, where the first match is
  140. match= 1. If a negative number is specified then a match is returned
  141. counting from the last match. Hence match = -1 is the same as requesting
  142. the last match. Defaults to 1.
  143. plain: A flag indicating that the pattern should be understood as plain
  144. text. Defaults to false.
  145. nomatch: If no match is found, output the "nomatch" value rather than an error.
  146. If invoked using named parameters, Mediawiki will automatically remove any leading or
  147. trailing whitespace from each string. In some circumstances this is desirable, in
  148. other cases one may want to preserve the whitespace.
  149. If the match_number or start_index are out of range for the string being queried, then
  150. this function generates an error. An error is also generated if no match is found.
  151. If one adds the parameter ignore_errors=true, then the error will be suppressed and
  152. an empty string will be returned on any failure.
  153. For information on constructing Lua patterns, a form of [regular expression], see:
  154. * http://www.lua.org/manual/5.1/manual.html#5.4.1
  155. * http://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#Patterns
  156. * http://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#Ustring_patterns
  157. ]]
  158. function str.match( frame )
  159. local new_args = str._getParameters( frame.args, {'s', 'pattern', 'start', 'match', 'plain', 'nomatch'} );
  160. local s = new_args['s'] or '';
  161. local start = tonumber( new_args['start'] ) or 1;
  162. local plain_flag = str._getBoolean( new_args['plain'] or false );
  163. local pattern = new_args['pattern'] or '';
  164. local match_index = math.floor( tonumber(new_args['match']) or 1 );
  165. local nomatch = new_args['nomatch'];
  166. if s == '' then
  167. return str._error( 'Target string is empty' );
  168. end
  169. if pattern == '' then
  170. return str._error( 'Pattern string is empty' );
  171. end
  172. if math.abs(start) < 1 or math.abs(start) > mw.ustring.len( s ) then
  173. return str._error( 'Requested start is out of range' );
  174. end
  175. if match_index == 0 then
  176. return str._error( 'Match index is out of range' );
  177. end
  178. if plain_flag then
  179. pattern = str._escapePattern( pattern );
  180. end
  181. local result
  182. if match_index == 1 then
  183. -- Find first match is simple case
  184. result = mw.ustring.match( s, pattern, start )
  185. else
  186. if start > 1 then
  187. s = mw.ustring.sub( s, start );
  188. end
  189. local iterator = mw.ustring.gmatch(s, pattern);
  190. if match_index > 0 then
  191. -- Forward search
  192. for w in iterator do
  193. match_index = match_index - 1;
  194. if match_index == 0 then
  195. result = w;
  196. break;
  197. end
  198. end
  199. else
  200. -- Reverse search
  201. local result_table = {};
  202. local count = 1;
  203. for w in iterator do
  204. result_table[count] = w;
  205. count = count + 1;
  206. end
  207. result = result_table[ count + match_index ];
  208. end
  209. end
  210. if result == nil then
  211. if nomatch == nil then
  212. return str._error( 'Match not found' );
  213. else
  214. return nomatch;
  215. end
  216. else
  217. return result;
  218. end
  219. end
  220. --[[
  221. pos
  222. This function returns a single character from the target string at position pos.
  223. Usage:
  224. {{#invoke:String|pos|target_string|index_value}}
  225. OR
  226. {{#invoke:String|pos|target=target_string|pos=index_value}}
  227. Parameters
  228. target: The string to search
  229. pos: The index for the character to return
  230. If invoked using named parameters, Mediawiki will automatically remove any leading or
  231. trailing whitespace from the target string. In some circumstances this is desirable, in
  232. other cases one may want to preserve the whitespace.
  233. The first character has an index value of 1.
  234. If one requests a negative value, this function will select a character by counting backwards
  235. from the end of the string. In other words pos = -1 is the same as asking for the last character.
  236. A requested value of zero, or a value greater than the length of the string returns an error.
  237. ]]
  238. function str.pos( frame )
  239. local new_args = str._getParameters( frame.args, {'target', 'pos'} );
  240. local target_str = new_args['target'] or '';
  241. local pos = tonumber( new_args['pos'] ) or 0;
  242. if pos == 0 or math.abs(pos) > mw.ustring.len( target_str ) then
  243. return str._error( 'String index out of range' );
  244. end
  245. return mw.ustring.sub( target_str, pos, pos );
  246. end
  247. --[[
  248. str_find
  249. This function duplicates the behavior of {{str_find}}, including all of its quirks.
  250. This is provided in order to support existing templates, but is NOT RECOMMENDED for
  251. new code and templates. New code is recommended to use the "find" function instead.
  252. Returns the first index in "source" that is a match to "target". Indexing is 1-based,
  253. and the function returns -1 if the "target" string is not present in "source".
  254. Important Note: If the "target" string is empty / missing, this function returns a
  255. value of "1", which is generally unexpected behavior, and must be accounted for
  256. separatetly.
  257. ]]
  258. function str.str_find( frame )
  259. local new_args = str._getParameters( frame.args, {'source', 'target'} );
  260. local source_str = new_args['source'] or '';
  261. local target_str = new_args['target'] or '';
  262. if target_str == '' then
  263. return 1;
  264. end
  265. local start = mw.ustring.find( source_str, target_str, 1, true )
  266. if start == nil then
  267. start = -1
  268. end
  269. return start
  270. end
  271. --[[
  272. find
  273. This function allows one to search for a target string or pattern within another
  274. string.
  275. Usage:
  276. {{#invoke:String|find|source_str|target_string|start_index|plain_flag}}
  277. OR
  278. {{#invoke:String|find|source=source_str|target=target_str|start=start_index|plain=plain_flag}}
  279. Parameters
  280. source: The string to search
  281. target: The string or pattern to find within source
  282. start: The index within the source string to start the search, defaults to 1
  283. plain: Boolean flag indicating that target should be understood as plain
  284. text and not as a Lua style regular expression, defaults to true
  285. If invoked using named parameters, Mediawiki will automatically remove any leading or
  286. trailing whitespace from the parameter. In some circumstances this is desirable, in
  287. other cases one may want to preserve the whitespace.
  288. This function returns the first index >= "start" where "target" can be found
  289. within "source". Indices are 1-based. If "target" is not found, then this
  290. function returns 0. If either "source" or "target" are missing / empty, this
  291. function also returns 0.
  292. This function should be safe for UTF-8 strings.
  293. ]]
  294. function str.find( frame )
  295. local new_args = str._getParameters( frame.args, {'source', 'target', 'start', 'plain' } );
  296. local source_str = new_args['source'] or '';
  297. local pattern = new_args['target'] or '';
  298. local start_pos = tonumber(new_args['start']) or 1;
  299. local plain = new_args['plain'] or true;
  300. if source_str == '' or pattern == '' then
  301. return 0;
  302. end
  303. plain = str._getBoolean( plain );
  304. local start = mw.ustring.find( source_str, pattern, start_pos, plain )
  305. if start == nil then
  306. start = 0
  307. end
  308. return start
  309. end
  310. --[[
  311. replace
  312. This function allows one to replace a target string or pattern within another
  313. string.
  314. Usage:
  315. {{#invoke:String|replace|source_str|pattern_string|replace_string|replacement_count|plain_flag}}
  316. OR
  317. {{#invoke:String|replace|source=source_string|pattern=pattern_string|replace=replace_string|
  318. count=replacement_count|plain=plain_flag}}
  319. Parameters
  320. source: The string to search
  321. pattern: The string or pattern to find within source
  322. replace: The replacement text
  323. count: The number of occurences to replace, defaults to all.
  324. plain: Boolean flag indicating that pattern should be understood as plain
  325. text and not as a Lua style regular expression, defaults to true
  326. ]]
  327. function str.replace( frame )
  328. local new_args = str._getParameters( frame.args, {'source', 'pattern', 'replace', 'count', 'plain' } );
  329. local source_str = new_args['source'] or '';
  330. local pattern = new_args['pattern'] or '';
  331. local replace = new_args['replace'] or '';
  332. local count = tonumber( new_args['count'] );
  333. local plain = new_args['plain'] or true;
  334. if source_str == '' or pattern == '' then
  335. return source_str;
  336. end
  337. plain = str._getBoolean( plain );
  338. if plain then
  339. pattern = str._escapePattern( pattern );
  340. replace = mw.ustring.gsub( replace, "%%", "%%%%" ); --Only need to escape replacement sequences.
  341. end
  342. local result;
  343. if count ~= nil then
  344. result = mw.ustring.gsub( source_str, pattern, replace, count );
  345. else
  346. result = mw.ustring.gsub( source_str, pattern, replace );
  347. end
  348. return result;
  349. end
  350. --[[
  351. simple function to pipe string.rep to templates.
  352. ]]
  353. function str.rep( frame )
  354. local repetitions = tonumber( frame.args[2] )
  355. if not repetitions then
  356. return str._error( 'function rep expects a number as second parameter, received "' .. ( frame.args[2] or '' ) .. '"' )
  357. end
  358. return string.rep( frame.args[1] or '', repetitions )
  359. end
  360. function str.split(inputstr, sep, no_pattern, ignore_null)
  361. --#invoke 支援
  362. if type(inputstr) == type({table}) then
  363. if not getArgs then getArgs = require('Module:Arguments').getArgs end
  364. args = getArgs(inputstr, {parentFirst=true})
  365. for arg_name, arg_value in pairs( args ) do
  366. if arg_name == 1 or arg_name == '1' or arg_name == "str" or arg_name == "inputstr" or arg_name == "input" then
  367. input_str = arg_value
  368. elseif arg_name == 2 or arg_name == '2' or arg_name == "sep" or arg_name == "separator" then
  369. separ = arg_value
  370. elseif arg_name == 3 or arg_name == '3' or arg_name == "no_pattern" or arg_name == "no pattern" then
  371. no_pattern_flag = arg_value
  372. elseif arg_name == 4 or arg_name == '4' or arg_name == "ignore_null" or arg_name == "ignore null" then
  373. ignore_null_flag = arg_value
  374. elseif arg_name == 5 or arg_name == '5' or arg_name == "format" then
  375. format = arg_value or "*{{{1}}}\n";
  376. end
  377. end
  378. if not yesno then yesno = require('Module:Yesno') end
  379. no_pattern_flag = yesno( no_pattern_flag or 'yes' )
  380. ignore_null_flag = yesno( ignore_null_flag or 'no' )
  381. is_invoke = true
  382. format = mw.ustring.gsub(format or "*{{{1}}}\n", "%{%{%{.-%}%}%}", "%%s" );
  383. it = mw.ustring.find(format, "%%s", 1)
  384. if it == nil then format = format .. "%s" end
  385. format = mw.ustring.gsub(format, "\\n", "\n")
  386. else
  387. input_str = inputstr
  388. separ = sep
  389. no_pattern_flag = no_pattern
  390. ignore_null_flag = ignore_null
  391. is_invoke = false
  392. end
  393. input_str = input_str or ''
  394. separ = separ or "%s"
  395. if no_pattern_flag == nil then no_pattern_flag = true end
  396. if ignore_null_flag == nil then ignore_null_flag = false end
  397. length = mw.ustring.len(input_str)
  398. --split函數起點
  399. if no_pattern_flag then
  400. 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,
  401. "%[", "%["), "%]", "%]"), "%{", "%{"), "%}", "%}"), "%%", "%%%%"), "%)", "%)"), "%-", "%-"),
  402. "%^", "%^"), "%$", "%$"), "%(", "%("), "%.", "%."), "%*", "%*"), "%+", "%+"), "%|", "%|");
  403. end
  404. iterator = 1 ; i = 1 ; flag = true
  405. result = {}
  406. separ_str_begin, separ_str_end = mw.ustring.find(input_str, separ, iterator)
  407. --
  408. debug1 = 1
  409. --
  410. while flag do
  411. debug1 = debug1 + 1
  412. if separ_str_begin == nil or iterator > length or debug1 >= 100 then
  413. separ_str_begin = 0
  414. separ_str_end = -2
  415. flag = false
  416. end
  417. if separ_str_end < separ_str_begin then separ_str_end = separ_str_begin end
  418. finded_str = mw.ustring.sub(input_str, iterator, separ_str_begin - 1)
  419. if not(mw.text.trim(finded_str) == '' and ignore_null_flag) then
  420. result[i] = finded_str
  421. i = i + 1
  422. end
  423. iterator = separ_str_end + 1
  424. separ_str_begin, separ_str_end = mw.ustring.find(input_str, separ, iterator)
  425. end
  426. if is_invoke then
  427. body = ''
  428. for i, result_str in pairs( result ) do
  429. body = body .. mw.ustring.gsub(format, "%%s", result_str)
  430. end
  431. return body
  432. end
  433. return result;
  434. end
  435. --[[
  436. join
  437. Join all non empty arguments together; the first argument is the separator.
  438. Usage:
  439. {{#invoke:String|join|sep|one|two|three}}
  440. ]]
  441. function str.join(frame)
  442. local args = {}
  443. local sep
  444. for _, v in ipairs( frame.args ) do
  445. if sep then
  446. if v ~= '' then
  447. table.insert(args, v)
  448. end
  449. else
  450. sep = v
  451. end
  452. end
  453. return table.concat( args, sep or '' )
  454. end
  455. --[[
  456. Helper function that populates the argument list given that user may need to use a mix of
  457. named and unnamed parameters. This is relevant because named parameters are not
  458. identical to unnamed parameters due to string trimming, and when dealing with strings
  459. we sometimes want to either preserve or remove that whitespace depending on the application.
  460. ]]
  461. function str._getParameters( frame_args, arg_list )
  462. local new_args = {};
  463. local index = 1;
  464. local value;
  465. for i,arg in ipairs( arg_list ) do
  466. value = frame_args[arg]
  467. if value == nil then
  468. value = frame_args[index];
  469. index = index + 1;
  470. end
  471. new_args[arg] = value;
  472. end
  473. return new_args;
  474. end
  475. --[[
  476. Helper function to handle error messages.
  477. ]]
  478. function str._error( error_str )
  479. local frame = mw.getCurrentFrame();
  480. local error_category = frame.args.error_category or 'Errors reported by Module String';
  481. local ignore_errors = frame.args.ignore_errors or false;
  482. local no_category = frame.args.no_category or false;
  483. if str._getBoolean(ignore_errors) then
  484. return '';
  485. end
  486. local error_str = '<strong class="error">String Module Error: ' .. error_str .. '</strong>';
  487. if error_category ~= '' and not str._getBoolean( no_category ) then
  488. error_str = '[[Category:' .. error_category .. ']]' .. error_str;
  489. end
  490. return error_str;
  491. end
  492. --[[
  493. Helper Function to interpret boolean strings
  494. ]]
  495. function str._getBoolean( boolean_str )
  496. local boolean_value;
  497. if type( boolean_str ) == 'string' then
  498. boolean_str = boolean_str:lower();
  499. if boolean_str == 'false' or boolean_str == 'no' or boolean_str == '0'
  500. or boolean_str == '' then
  501. boolean_value = false;
  502. else
  503. boolean_value = true;
  504. end
  505. elseif type( boolean_str ) == 'boolean' then
  506. boolean_value = boolean_str;
  507. else
  508. error( 'No boolean value found' );
  509. end
  510. return boolean_value
  511. end
  512. --[[
  513. Helper function that escapes all pattern characters so that they will be treated
  514. as plain text.
  515. ]]
  516. function str._escapePattern( pattern_str )
  517. return mw.ustring.gsub( pattern_str, "([%(%)%.%%%+%-%*%?%[%^%$%]])", "%%%1" );
  518. end
  519. return str