• Documentation - https://pkg.go.dev/regexp
  • We can use regexp for testing the validity of regex exp.
    FunctionDescription
    regexp.MatchString(pattern, s)Checks if pattern matches string
    regexp.Compile(pattern)Compiles a regular expression
    regexp.MustCompile(pattern)Compiles regex and panics on error
    re.MatchString(s)Checks if regex matches string
    re.FindString(s)Returns first match
    re.FindAllString(s, n)Returns all matches
    re.ReplaceAllString(s, repl)Replaces matches with new string
    re.Split(s, n)Splits string using regex
import "regexp"
 
matched, _ := regexp.MatchString("go", "golang")
fmt.Println(matched) // true
 
re := regexp.MustCompile("[a-z]+")
fmt.Println(re.MatchString("hello123")) // true
fmt.Println(re.FindString("abc123xyz")) // abc
fmt.Println(re.FindAllString("abc123xyz456", -1)) // [abc xyz]
fmt.Println(re.ReplaceAllString("abc123xyz", "#")) // #123#
fmt.Println(re.Split("a,b,c", -1)) // [ , , ]
 
re = regexp.MustCompile(`[a-z]+\d*`)
b = re.MatchString("[a12]")       // => true
b = re.MatchString("12abc34(ef)") // => true
b = re.MatchString(" abc!")       // => true
b = re.MatchString("123 456")     // => false