实现说明
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])
}