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

帮助:解析函数/rmatch

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

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

rmatch

基于正则表达式匹配文本。出自扩展 RegexFunctions

支持捕获组引用,如果匹配成功 $#\# 包含捕获的文本。如果您想要一个组后跟另一个数字,请使用 ${#}##为数字。

语法

{{#rmatch:string|pattern|then|else}}

  • string(必需):要匹配的文本
  • pattern(必需):正则表达式模式(空格敏感)
  • then(可选):匹配成功时返回的文本,可使用$1\1${1}1引用捕获组
  • else(可选):匹配失败时返回的文本(默认为空)

示例

  • {{#rmatch:Hello|H.*|匹配成功|失败}} → 匹配成功
  • {{#rmatch:ABC123|([A-Z]+)|大写字母:$1}} → 大写字母:ABC
  • {{#rmatch:测试|\\d+|有数字|无数字}} → 无数字

底层代码

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

/** https://github.com/wikimedia/mediawiki-extensions-RegexFunctions/blob/00752374efb579663a3e35fd17e8683ccd1fed77/ExtRegexFunctions.php
 * Regex match function
 *
 * Supports a legacy invocation with numbered parameters:
 * {{#rmatch:string|pattern|then|else}}
 *
 * Supports named parameters:
 * All named parameters mentioned in getPatternAndOptions
 * then: text to display if the match is successful
 * else: text to display if the match is not successful, blank if not defined
 *
 * @param Parser &$parser
 * @param PPFrame $frame
 * @param PPNode[] $args
 * @return string Expanded wikitext result of parser function
 */
public static function rmatch( Parser &$parser, PPFrame $frame, $args ) {
	$string = $frame->expand( array_shift( $args ) );
	// make a PPFrame containing the remainder of parser function args for ease of use
	$matchFrame = $frame->newChild( $args, $frame->getTitle() );
	$pattern = self::getPatternAndOptions( $matchFrame );

	$num = preg_match( $pattern, $string, $matches );
	if ( $num === false ) {
		return '';
	}

	if ( $num === 0 ) {
		// not a match
		$else = self::getLocalizedArgument( $matchFrame, 'else', 3 );
		if ( $else === false ) {
			return '';
		}

		return $else;
	}

	$then = self::getLocalizedArgument( $matchFrame, 'then', 2 );
	if ( $then === false ) {
		return '';
	}

	// expand back-references in $then
	return preg_replace_callback(
		'/[$\\\\]([0-9]+)|\${([0-9]+)}/',
		static function ( $backRefs ) use ( $matches ) {
			if ( $backRefs[1] !== '' && array_key_exists( $backRefs[1], $matches ) ) {
				return $matches[$backRefs[1]];
			}

			if ( $backRefs[2] !== '' && array_key_exists( $backRefs[2], $matches ) ) {
				return $matches[$backRefs[2]];
			}

			return '';
		},
		$then
	);
}

实际用例

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

WIKI实验室 - tools

女神转生 - persona

绝区零 - zzz

奇迹暖暖 - qjnn

世界之外 - world

戴森球计划 - dsp

天地劫 - tdj

江南百景图 - jiangnan