如何使用Regexp包ReplaceAll函数替换Go中的字符?

时间:2009-11-15 16:42:46

标签: regex go replace

我不熟悉类C语法,并且想编写代码来查找&在源字符串中替换所有'A'到'B',用Regexp包替换AllA或ReplaceAllString函数说'ABBA'?如何设置Regexp,src和repl类型?以下是Go文档中的ReplaceAll code snippet

// 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 <= len(src) {
        a := re.doExecute("", src, searchPos);
        if len(a) == 0 {
            break // no more matches
        }

// 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] > 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 > a[1] { searchPos += width } else if searchPos+1 > 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();

}

2 个答案:

答案 0 :(得分:3)

这是做你想做的事情的惯例:

package main
import ("fmt"; "regexp"; "os"; "strings";);
func main () {
    reg, error := regexp.Compile ("B");
    if error != nil {
        fmt.Printf ("Compile failed: %s", error.String ());
        os.Exit (1);
    }
    output := string (reg.ReplaceAll (strings.Bytes ("ABBA"),
                      strings.Bytes ("A")));
    fmt.Println (output);
}

答案 1 :(得分:1)

这是一个小例子。你也可以在他Regexp test class

中找到很好的例子
package main

import (
    "fmt"
    "regexp"
    "strings"
)

func main() {
    re, _ := regexp.Compile("e")
    input := "hello"
    replacement := "a"
    actual := string(re.ReplaceAll(strings.Bytes(input), strings.Bytes(replacement)))
    fmt.Printf("new pattern %s", actual)
}