Golang | Replacing all String which Matches with Regular Expression

A regular expression is a sequence of characters which define a search pattern. Go language support regular expressions. A regular expression is used for parsing, filtering, validating, and extracting meaningful information from large text, like logs, the output generated from other programs, etc.
In Go regexp, you are allowed to replace original string with another string if the specified string matches with the specified regular expression with the help of ReplaceAllString() method. In this method, $ sign means interpreted as in Expand like $1 indicates the text of the first submatch. This method is defined under the regexp package, so for accessing this method you need to import the regexp package in your program.

Syntax:

func (re *Regexp) ReplaceAllString(str, r string) string

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Go program to illustrate how to
// replace string with the specified regexp
package main
  
import (
    "fmt"
    "regexp"
)
  
// Main function
func main() {
  
    // Replace string with the specified regexp
    // Using ReplaceAllString() method
    m1 := regexp.MustCompile(`x(p*)y`)
  
    fmt.Println(m1.ReplaceAllString("xy--xpppyxxppxy-", "B"))
    fmt.Println(m1.ReplaceAllString("xy--xpppyxxppxy--", "$1"))
    fmt.Println(m1.ReplaceAllString("xy--xpppyxxppxy-", "$1P"))
    fmt.Println(m1.ReplaceAllString("xy--xpppyxxppxy-", "${1}Q"))
  
}

chevron_right


Output:

B--BxxppB-
--pppxxpp--
--xxpp-
Q--pppQxxppQ-

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Go program to illustrate how to replace
// string with the specified regexp
package main
  
import (
    "fmt"
    "regexp"
)
  
// Main function
func main() {
  
    // Creating and initializing a string
    // Using shorthand declaration
    s := "Geeks-for-Geeks-for-Geeks-for-Geeks-gfg"
  
    // Replacing all the strings
    // Using ReplaceAllString() method
    m := regexp.MustCompile("^(.*?)Geeks(.*)$")
    Str := "${1}GEEKS$2"
    res := m.ReplaceAllString(s, Str)
    fmt.Println(res)
  
}

chevron_right


Output:

GEEKS-for-Geeks-for-Geeks-for-Geeks-gfg


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.