Search & Replace in Strings
One common task when working with text in code, is searching and replacing inside strings. 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: 1 func Replace(s, old, new string, n int) string Here’s an example of how to use the Replace method:
Remove All Non-Alphanumeric Characters
We often need to remove symbols and special characters from the strings we’re using (especially with currency!). This post shows how you can keep the letters and numbers, but remove any punctuation, symbols, grammar, etc. For example, if a user types in “$1,000” you can turn it into “1000”. We use the regexp package to do this, first building a regex with .Compile() then running the string through that regex with .