title: How do you replace a character in Go using the Regexp package ReplaceAll function?
body: <p>I am not familiar with C-like syntaxes and would like to write code to find &amp; replace, say, all 'A's to 'B's in a source string, say 'ABBA' with the Regexp package ReplaceAll or ReplaceAllString functions? How do I set up type Regexp, src and repl? Here's the ReplaceAll <a href="http://golang.org/src/pkg/regexp/regexp.go#L907" rel="nofollow noreferrer">code snippet</a> from the Go documentation: </p>
  
  <p><pre>// ReplaceAll returns a copy of src in which all matches for the Regexp
  // have been replaced by repl.  No support is provided for expressions
  // (e.g. \1 or $1) in the replacement text.
  func (re *Regexp) ReplaceAll(src, repl []byte) []byte {
      lastMatchEnd := 0; // end position of the most recent match
      searchPos := 0;    // position where we next look for a match
      buf := new(bytes.Buffer);
      for searchPos &lt;= len(src) {
          a := re.doExecute("", src, searchPos);
          if len(a) == 0 {
              break // no more matches
          }</p>
  
  <code>    // Copy the unmatched characters before this match.
      buf.Write(src[lastMatchEnd:a[0]]);
  
      // Now insert a copy of the replacement string, but not for a
      // match of the empty string immediately after another match.
      // (Otherwise, we get double replacement for patterns that
      // match both empty and nonempty strings.)
      if a[1] &gt; lastMatchEnd || a[0] == 0 {
          buf.Write(repl)
      }
      lastMatchEnd = a[1];
  
      // Advance past this match; always advance at least one character.
      _, width := utf8.DecodeRune(src[searchPos:len(src)]);
      if searchPos+width &gt; a[1] {
          searchPos += width
      } else if searchPos+1 &gt; a[1] {
          // This clause is only needed at the end of the input
          // string.  In that case, DecodeRuneInString returns width=0.
          searchPos++
      } else {
          searchPos = a[1]
      }
  }
  
  // Copy the unmatched characters after the last match.
  buf.Write(src[lastMatchEnd:len(src)]);
  
  return buf.Bytes();
  </code></pre>
  
  <p>}
  </p>