Golang Regex Replace Example — GolangLearn

in this golang tutorial, I will explain how to work with regular expressions in Golang. The glonag have built-in package regexp for regular expressions.

What’s Regular Expression

The golang package uses RE2 syntax standards that is also used by other languages like Python, C, and Perl.There are following regex functions available -

  • MatchString()
  • FindString()
  • FindStringIndex()
  • FindStringSubmatch()
  • ReplaceAllString()
  • Compile()
  • MustCompile()
  • FindAllString

Let’s explain regex functions with examples to work with regular expressions -

MatchString — Golang regex match

package main import ( "fmt" "regexp" ) func main() { str := "Golang regular expressions example" match, err := regexp.MatchString(`^Golang`, str) fmt.Println("Match: ", match, " Error: ", err) }

Output:
The above code will return true if substring found into the source string :
Match: true Error:

Compile or MustCompile method

regexp1, err := regexp.Compile(regexp)
regexp2 := regexp.MustCompile(regexp)

FindString — Find String in Golang

package main import ( "fmt" "regexp" ) func main() { str := "Golang expressions example" regexp,_ := regexp.Compile("Gola([a-z]+)g") fmt.Println(regexp.FindString(str)) }

Output: Match: Golang Error:

FindStringIndex

package main import ( "fmt" "regexp" ) func main() { str := "Golang regular expressions example" regexp, err := regexp.Compile(`exp`) match := regexp.FindStringIndex(str) fmt.Println("Match: ", match, " Error: ", err) }

FindStringSubmatch

package main import ( "fmt" "regexp" ) func main() { str := "Golang regular expressions example" regexp, err := regexp.Compile(`p([a-z]+)e`) match := regexp.FindStringSubmatch(str) fmt.Println("Match: ", match, " Error: ", err) }

Output:
Match: [pre r] Error:

FindAllString

package main import ( "fmt" "regexp" ) func main() { str := "Golang regular expressions example" regexp, err := regexp.Compile(`p([a-z]+)e`) match := regexp.FindAllString(str, 2) fmt.Println("Match: ", match, " Error: ", err) }

ReplaceAllString

package main import ( "fmt" "regexp" ) func main() { str := "Golang regular expressions example" regexp, err := regexp.Compile(`examp([a-z]+)e`) match := regexp.ReplaceAllString(str, "tutorial") fmt.Println("Match: ", match, " Error: ", err) }

Output: Match: Golang regular expressions tutorial Error:

Originally published at https://www.golanglearn.com on November 9, 2020.

Hey, I am Parvez Alam. A software developer since 2009. I am a programming addict. I love learning and sharing knowledge. https://www.phpflow.com/