1
0
mirror of https://github.com/golang/go synced 2024-11-22 04:34:39 -07:00

exp/regexp: add MustCompilePOSIX

R=r
CC=golang-dev
https://golang.org/cl/4962060
This commit is contained in:
Russ Cox 2011-09-08 15:00:49 -04:00
parent 21e671dee6
commit 66b3fabf17
2 changed files with 21 additions and 2 deletions

View 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) { func testFowler(t *testing.T, file string) {
f, err := os.Open(file) f, err := os.Open(file)

View File

@ -58,6 +58,7 @@ import (
"exp/regexp/syntax" "exp/regexp/syntax"
"io" "io"
"os" "os"
"strconv"
"strings" "strings"
"sync" "sync"
"utf8" "utf8"
@ -195,11 +196,29 @@ func (re *Regexp) put(z *machine) {
func MustCompile(str string) *Regexp { func MustCompile(str string) *Regexp {
regexp, error := Compile(str) regexp, error := Compile(str)
if error != nil { if error != nil {
panic(`regexp: compiling "` + str + `": ` + error.String()) panic(`regexp: Compile(` + quote(str) + `): ` + error.String())
} }
return regexp 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. // NumSubexp returns the number of parenthesized subexpressions in this Regexp.
func (re *Regexp) NumSubexp() int { func (re *Regexp) NumSubexp() int {
return re.numSubexp return re.numSubexp