on
Search & Replace All in Strings
One common task when working with text in code, is searching and replacing inside strings. For example you might want to replace X with Y. Or equally, you might want to replace Z with nothing, removing it. In this blog post, we’ll explore two ways to perform a search and replace operation in Go using the strings and regexp packages.
Strings Package
The strings package provides a simple method called Replace() for search and replace operations. This method has the following signature:
|
|
Here’s an example of how to use the Replace method:
|
|
In this example, we replace all occurrences of “Gopher” with “Kitty”. The -1 as the last argument indicates that all occurrences should be replaced. If you want to limit the number of replacements, change the value to the desired number. Another way to do this is to use the ReplaceAll
function.
Example In Action
Regexp Package
For more complex search and replace operations, the regexp package offers powerful regular expression functionality. The ReplaceAllString method allows you to search and replace substrings using regular expressions:
|
|
Here’s an example using the ReplaceAllString function:
|
|
In this example, we create a regular expression object with the MustCompile function and use the ReplaceAllString method to replace all occurrences of “Gopher” with “Go”.