Golang regexp.ReplaceAllFunc() function example

package regexp

Golang regexp.ReplaceAllFunc() function usage example.

NOTE : The inner function is useful in cases where you need to evaluate certain data first to extract the replacement string.

 package main

 import (
  "fmt"
  "regexp"
 )

 func main() {

  // regular expression pattern
  regE := regexp.MustCompile("[a-c]*$")

  src := []byte("abcdabc")

  //repl := []byte("x")

  //newByte := regE.ReplaceAll(src, repl)

  // NOTE : The inner function is useful in cases where you need to evaluate certain data first
  // to extract the replacement string.
  // In this example, we will just use string "x" for simplicity sake

  newByte := regE.ReplaceAllFunc([]byte(src), func(s []byte) []byte { return []byte("x") })

  fmt.Println(string(newByte))

 }

Output :

abcdx

References :

http://golang.org/pkg/regexp/#Regexp.ReplaceAllFunc

  See also : Golang regexp.ReplaceAll() function example

Advertisement