Lazy / Non-Greedy Quantifier in GO
Demonstrate lazy quantifiers `+?` by matching the SHORTEST HTML-like tag rather than the longest greedy span.
Try it in the GO tester →Pattern
regexGO
<.+?> (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`<.+?>`)
input := `<b>bold</b> and <i>italic</i>`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
How the pattern works
<.+?> matches an opening `<`, then ONE OR MORE characters (`.+`), then the next `>`. The `?` after `+` makes the quantifier lazy — it stops at the first `>` it sees, instead of the greedy default that would consume everything up to the LAST `>` in the string.
Examples
Input
<b>bold</b> and <i>italic</i>Matches
<b></b><i></i>
Input
<div class="foo">x</div>Matches
<div class="foo"></div>
Input
no tagsNo match
—