Replacing all String which Matches with Regular Expression in Golang


In Golang, you can replace all the string occurrences that match a regular expression with the help of the regexp package. The regexp package in Golang provides a ReplaceAllString() function that replaces all occurrences of the matched string with a new string.

Example

Here's an example of how to replace all the string occurrences that match a regular expression in Golang −

package main

import (
   "fmt"
   "regexp"
)

func main() {
   str := "The quick brown fox jumps over the lazy dog"
   re := regexp.MustCompile("fox|dog")
   newStr := re.ReplaceAllString(str, "cat")
   fmt.Println(newStr)
}

In the above example, we have a string str that contains a sentence. We want to replace all occurrences of the words "fox" and "dog" with the word "cat". To achieve this, we first compile a regular expression pattern using regexp.MustCompile(). The regular expression pattern matches the words "fox" and "dog".

Next, we call the ReplaceAllString() function with the input string and the replacement string as arguments. The function replaces all occurrences of the matched pattern with the replacement string and returns the new string.

The output of the above code will be −

Output

The quick brown cat jumps over the lazy cat

You can use regular expressions to replace more complex patterns in strings.

Example

Here's another example that replaces all occurrences of a digit with a '#' character −

package main

import (
   "fmt"
   "regexp"
)

func main() {
   str := "My phone number is 123-456-7890"
   re := regexp.MustCompile("[0-9]")
   newStr := re.ReplaceAllString(str, "#")
   fmt.Println(newStr)
}

In the above example, we have a string str that contains a phone number. We want to replace all the digits in the phone number with the '#' character. To achieve this, we compile a regular expression pattern that matches any digit using the character class [0-9].

Next, we call the ReplaceAllString() function with the input string and the replacement string as arguments. The function replaces all occurrences of the matched pattern with the replacement string and returns the new string.

Output

My phone number is ###-###-####

Conclusion

In conclusion, replacing all string occurrences that match a regular expression in Golang is easy and can be achieved using the ReplaceAllString() function of the regexp package.

Updated on: 18-Apr-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements