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.
Code
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
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.