Go Standard Library Cookbook
上QQ阅读APP看书,第一时间看更新

How it works...

The Replace function of a strings package is widely used for simple replacement. The last integer argument defines how many replacements will be done (in case of -1, all strings are replaced. See the second use of Replace, where only the first two occurrences are replaced.) The use of the Replace function is presented in steps 1 - 5.

Besides the Replace function, the Replacer structure also has the WriteString method. This method will write to the given writer with all replacements defined in Replacer The main purpose of this type is its reusability. It can replace multiple strings at once and it is safe for concurrent use; see steps 6 - 8.

The more sophisticated method of replacing the substring, or even the matched pattern, is naturally the use of the regular expression. The Regex type pointer method ReplaceAllString could be leveraged for this purpose. Steps 9 - 11 illustrate the use of the regexp package.