0xBF
0xBF

0xBF

Go Cheatsheet - RegExp

0xBF's photo
0xBF

Published on Apr 22, 2021

1 min read

Regular Expression

We can use go's regexp module for regular expression match.

Quick Match

matched, _ := regexp.MatchString("a[a-z]+e", "apple")
fmt.Println("Matched:", matched) // true

Compile then check match

r := regexp.MustCompile("a([a-z]+)e")

fmt.Println(r.MatchString("apple"))   // true
fmt.Println(r.MatchString("abdomen")) // true
fmt.Println(r.MatchString("amazing")) // false

Find String

fmt.Println(r.FindString("apple"))   // apple
fmt.Println(r.FindString("abdomen")) // abdome
fmt.Println(r.FindString("amazing")) // ""

Find Submatch / Match groups

fmt.Println(r.FindStringSubmatch("apple")) // [apple ppl], length-2 slice
fmt.Println(
    r.FindStringSubmatch("abdomen"),
) // [abdome bdom], length-2 slice
fmt.Println(r.FindStringSubmatch("amazing")) // [], empty slice

Replace string

s := "I want some apple please"
fmt.Println(r.ReplaceAllString(s, "pear")) // I want some pear plepear
fmt.Println(r.ReplaceAllStringFunc(s, func(str string) string {
    return strings.ToUpper("banana")
})) // I want some BANANA pleBANANA
 
Share this