From f629a0f08f72fc9772926415d8ace70d4b15d4aa Mon Sep 17 00:00:00 2001 From: Aadhavan Srinivasan Date: Fri, 31 Jan 2025 16:46:05 -0500 Subject: [PATCH] Added 'mustCompile' which panicks if there is an error compiling --- regex/compile.go | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/regex/compile.go b/regex/compile.go index 3be2477..a491e0f 100644 --- a/regex/compile.go +++ b/regex/compile.go @@ -1110,10 +1110,11 @@ func thompson(re []postfixNode) (Reg, error) { } -// Compiles the given regular expression into a Reg type, suitable for use with the -// matching functions. The second return value is non-nil if a compilation error has -// occured. As such, the error value must be checked before using the Reg returned by this function. -// The second parameter is an optional list of flags, passed to the parsing function shuntingYard. +// Compile compiles the given regular expression into a [Reg]. +// +// An error value != nil indicates that the regex was invalid; the error message should provide +// detailed information on the nature of the error. +// The second parameter is a sequence of zero or more [ReFlag] values, that modify the behavior of the regex. func Compile(re string, flags ...ReFlag) (Reg, error) { nodes, err := shuntingYard(re, flags...) if err != nil { @@ -1125,3 +1126,12 @@ func Compile(re string, flags ...ReFlag) (Reg, error) { } return reg, nil } + +// MustCompile panicks if Compile returns an error. They are identical in all other respects. +func MustCompile(re string, flags ...ReFlag) Reg { + reg, err := Compile(re, flags...) + if err != nil { + panic(err) + } + return reg +}