← 中文资源

简体中文版本

Regexp 最长匹配优先

把正则切到 Longest 模式:交替分支不再取第一个能匹配的,而是取最长的;该模式作用于整个表达式,子组也随之变化。

阅读英文原文

实现说明

Regexp 最长匹配优先以函数 main为骨架。

使用要点

  • 演示输出是带标签的(default:、Longest:、word:),每个操作都会留下自己的一行标注。

常见问题

运行「Regexp 最长匹配优先」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 default:、Longest:、word: 这类标签。

核心语句

words := regexp.MustCompile("(go|golang)")

代码示例

package main

import (
	"fmt"
	"regexp"
)

func main() {
	text := "ab"

	// default leftmost-first: the first branch that matches wins
	first := regexp.MustCompile("a|ab")
	fmt.Println("default:", first.FindString(text))

	// Longest switches to leftmost-longest preference
	longest := regexp.MustCompile("a|ab")
	longest.Longest()
	fmt.Println("Longest:", longest.FindString(text))

	// the mode applies to the whole expression, not just the outer branch
	words := regexp.MustCompile("(go|golang)")
	words.Longest()
	fmt.Println("word:", words.FindString("golang"))
	fmt.Println("submatch:", words.FindStringSubmatch("golang")[1])
}