Regexp Longest Match Preference

Switch a regexp to Longest mode and watch alternation prefer the longest branch instead of the first one that matches at the leftmost position.

GoData Integrity

Code

gosnippet
25 lines
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])
}

Inside the snippet

Structurally, expect the function main and nothing else.

Caveats

  • Entirely standard-library — copy it in and it runs.

Putting it to use

Entry signature: func main()

Look for the default:, Longest:, word: prefixes when the file runs; they tie each line to its step.

Core lines

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

Interactive Tools for This Topic

FAQ

What does Regexp Longest Match Preference print when run?
Running the file directly is enough — expect labeled output lines such as `default:`, `Longest:`, `word:`.