Find and replace

The example in this subsection will search the provided text for two variations of a given string and replace it with another string. The program will be named findReplace.go and will actually use Go regular expressions. The main reason for using the regexp.Compile() function, in this case, is that it greatly simplifies things and allows you to access your text only once.

The first part of the findReplace.go program is as follows:

package main 
 
import ( 
   "fmt" 
   "os" 
   "regexp" 
) 

The next part is as follows:

func main() { 
 
   var s [3]string 
   s[0] = "1 b 3" 
   s[1] = "11 a B 14 1 1" 
   s[2] = "b 2 -3 B -5" 
 
   parse, err := regexp.Compile("[bB]") 
 
   if err != nil { 
         fmt.Printf("Error compiling RE: %s\n", err) 
         os.Exit(-1) 
   } 

The previous Go code ...

Get Go Systems Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.