regexp.Compile, regexp.MustCompile, Regexp.FindAllString, Regexp.FindStringSubmatch, Regexp.MatchString
func Compile(expr string) (*Regexp, error)
func MustCompile(str string) *Regexp
func (re *Regexp) FindAllString(s string, n int) []string
func (re *Regexp) FindStringSubmatch(s string) []string
func (re *Regexp) MatchString(s string) boolParse a pattern, list matches, and read capturing groups. Compile returns an error; MustCompile panics on the same parse failure.
| Parameter | Description |
|---|---|
expr / str | A RE2 regular expression. Invalid syntax, or Perl features this package does not implement, produce a parse error. |
s, n | The string to search. If n >= 0, FindAllString returns at most n matches; if n < 0, it returns all of them. |
Returns: Compile returns a *Regexp and a nil error, or a parse error. FindAllString returns a slice of matches, or nil if there is none. FindStringSubmatch returns the full match and submatches, or nil. MatchString returns whether a match exists.
Errors
parse error— The measured Compile error for "(" on Go 1.24.0 is "error parsing regexp: missing closing ): `(`". MustCompile panics with a message that includes that parse error.
- [a-z]+ is case-sensitive, so "AB" does not match and "ab" does. The invalid pattern is passed to Compile, not MustCompile, so the program can print the error without recovering a panic.
package main
import (
"fmt"
"regexp"
)
func main() {
re, err := regexp.Compile(`[a-z]+`)
fmt.Println(err)
fmt.Println(re.FindAllString("A ab cd!", -1))
fmt.Println(re.MatchString("ab"), re.MatchString("AB"))
sub := regexp.MustCompile(`(\d+)-(\d+)`)
fmt.Println(sub.FindStringSubmatch("id 12-34 x"))
_, err = regexp.Compile("(")
fmt.Println(err)
}Expected output
<nil>
[ab cd]
true false
[12-34 12 34]
error parsing regexp: missing closing ): `(`