Tools 是非官方社区Wiki。社区文档正在编写中,欢迎参与。 Wiki编辑答疑群:717421103
版本250722.2
全站通知:

帮助:解析函数/rsplit

来自WIKI实验室WIKI_BWIKI_哔哩哔哩
跳到导航 跳到搜索

rsplit是一个解析函数。帮助:解析函数页列出了所有解析函数的说明。

rsplit

基于正则表达式分割字符串。出自扩展 RegexFunctions

语法

{{#rsplit:源字符串|正则表达式|片段序号}}

  • 源字符串:待分割的原始字符串
  • 正则表达式:分隔匹配模式(区分大小写和空格)
  • 片段序号(可选):返回的片段索引(负数序号代表反向位置)

示例

  • {{#rsplit:One Two Three Four|\s+}} → One
  • {{#rsplit:One Two Three Four|\s+|1}} → Two
  • {{#rsplit:One Two Three Four|\s+|-1}} → Four

底层代码

来自MediaWiki及其扩展的源代码,运行在服务端。此处仅供快速查阅,便于更充分的挖掘其“特性”。

/** mediawiki-extensions-RegexFunctions-00752374efb579663a3e35fd17e8683ccd1fed77\ExtRegexFunctions.php
 * Split a string and return one piece of it
 *
 * {{#rsplit:string|pattern|piece}}
 *
 * Supports named arguments:
 * All named arguments in getPatternAndOptions
 * piece: Piece to return, starting at 0. Negative returns from the end.
 *
 * @param Parser &$parser
 * @param PPFrame $frame
 * @param PPNode[] $args
 * @return string
 */
public static function rsplit( Parser &$parser, PPFrame $frame, $args ) {
	$string = $frame->expand( array_shift( $args ) );
	$splitFrame = $frame->newChild( $args, $frame->getTitle() );
	$pattern = self::getPatternAndOptions( $splitFrame );

	$piece = self::getLocalizedArgument( $splitFrame, 'piece', 2 );
	$piece = intval( $piece );
	$res = preg_split( $pattern, $string );

	// allow negative pieces to work from the end of the array
	if ( $piece < 0 ) {
		$piece = $piece + count( $res );
	}

	// sanitation for pieces that don't exist
	if ( $piece < 0 ) {
		$piece = 0;
	}

	if ( $piece >= count( $res ) ) {
		$piece = count( $res ) - 1;
	}

	return $res[$piece];
}

实际用例

一些Wiki使用了相关特性,如下所示这个静态列表可能在下列页面更改后过时仅供批判性参考