]> Cypherpunks repositories - gostls13.git/commitdiff
regexp: add (*Regexp).Longest
authorAndrew Gerrand <adg@golang.org>
Mon, 4 Feb 2013 04:28:55 +0000 (15:28 +1100)
committerAndrew Gerrand <adg@golang.org>
Mon, 4 Feb 2013 04:28:55 +0000 (15:28 +1100)
Fixes #3696.

R=rsc
CC=golang-dev
https://golang.org/cl/7133051

src/pkg/regexp/exec_test.go
src/pkg/regexp/regexp.go

index e5d52b40df3fc2b5c4c4dba56f0fca6c6be69417..d3eddf2a74488ef55b3c2a45c0b524bbdb913f65 100644 (file)
@@ -706,3 +706,17 @@ func BenchmarkMatchHard_1K(b *testing.B)    { benchmark(b, hard, 1<<10) }
 func BenchmarkMatchHard_32K(b *testing.B)   { benchmark(b, hard, 32<<10) }
 func BenchmarkMatchHard_1M(b *testing.B)    { benchmark(b, hard, 1<<20) }
 func BenchmarkMatchHard_32M(b *testing.B)   { benchmark(b, hard, 32<<20) }
+
+func TestLongest(t *testing.T) {
+       re, err := Compile(`a(|b)`)
+       if err != nil {
+               t.Fatal(err)
+       }
+       if g, w := re.FindString("ab"), "a"; g != w {
+               t.Errorf("first match was %q, want %q", g, w)
+       }
+       re.Longest()
+       if g, w := re.FindString("ab"), "ab"; g != w {
+               t.Errorf("longest match was %q, want %q", g, w)
+       }
+}
index c516a1566f7e04e3d226e9bd15bfefe12bc503b6..c0ecc01c357cbbf6241afa702f3ba02c70b24e47 100644 (file)
@@ -130,6 +130,14 @@ func CompilePOSIX(expr string) (*Regexp, error) {
        return compile(expr, syntax.POSIX, true)
 }
 
+// Longest sets the match semantics of the regexp to leftmost-longest.
+// That is, when matching against text, the regexp returns a match that
+// begins as early as possible in the input (leftmost), and among those
+// it chooses a match that is as long as possible.
+func (re *Regexp) Longest() {
+       re.longest = true
+}
+
 func compile(expr string, mode syntax.Flags, longest bool) (*Regexp, error) {
        re, err := syntax.Parse(expr, mode)
        if err != nil {