]> Cypherpunks repositories - gostls13.git/commitdiff
exp/regexp: add MustCompilePOSIX
authorRuss Cox <rsc@golang.org>
Thu, 8 Sep 2011 19:00:49 +0000 (15:00 -0400)
committerRuss Cox <rsc@golang.org>
Thu, 8 Sep 2011 19:00:49 +0000 (15:00 -0400)
R=r
CC=golang-dev
https://golang.org/cl/4962060

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

index b6d9ecefb26f3a9333584faeb5c45c8445c2ff98..e8eaff54120e848e78ad98a57afe33fbbd359723 100644 (file)
@@ -351,7 +351,7 @@ func TestFowler(t *testing.T) {
        }
 }
 
-var notab = MustCompile(`[^\t]+`)
+var notab = MustCompilePOSIX(`[^\t]+`)
 
 func testFowler(t *testing.T, file string) {
        f, err := os.Open(file)
index 86c35fa72400b9b1e5a2dda6aaba37eac4688a5b..7480b098c74fccc8adf90f5311b7d14f0f4f4381 100644 (file)
@@ -58,6 +58,7 @@ import (
        "exp/regexp/syntax"
        "io"
        "os"
+       "strconv"
        "strings"
        "sync"
        "utf8"
@@ -195,11 +196,29 @@ func (re *Regexp) put(z *machine) {
 func MustCompile(str string) *Regexp {
        regexp, error := Compile(str)
        if error != nil {
-               panic(`regexp: compiling "` + str + `": ` + error.String())
+               panic(`regexp: Compile(` + quote(str) + `): ` + error.String())
        }
        return regexp
 }
 
+// MustCompilePOSIX is like CompilePOSIX but panics if the expression cannot be parsed.
+// It simplifies safe initialization of global variables holding compiled regular
+// expressions.
+func MustCompilePOSIX(str string) *Regexp {
+       regexp, error := CompilePOSIX(str)
+       if error != nil {
+               panic(`regexp: CompilePOSIX(` + quote(str) + `): ` + error.String())
+       }
+       return regexp
+}
+
+func quote(s string) string {
+       if strconv.CanBackquote(s) {
+               return "`" + s + "`"
+       }
+       return strconv.Quote(s)
+}
+
 // NumSubexp returns the number of parenthesized subexpressions in this Regexp.
 func (re *Regexp) NumSubexp() int {
        return re.numSubexp