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

我不熟悉类似C的语法,想编写代码以查找和替换源字符串中的所有'A'到'B',使用Regexp包ReplaceAll或ReplaceAllString函数说'ABBA'吗?如何设置Regexp,src和repl类型?这是Go文档中的ReplaceAll代码片段:


// ReplaceAll返回src的副本,其中Regexp的所有匹配项

都已被repl替换。

在替换文本中

不提供对// //表达式的支持(例如\ 1或$ 1)。func  (re * Regexp) ReplaceAll (src,repl [] byte) [] byte {

    lastMatchEnd:= 0 ; //最近匹配的

    searchPos的结束位置:= 0 ;    //接下来寻找匹配

    buf的位置:= new(bytes.Buffer);

    for searchPos <= len(src){

        一个:= re.doExecute(“”,src,searchPos);

        如果 len(a)== 0 {

            中断 //没有更多匹配项

        }



    // 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();

}


慕森王
浏览 328回答 2
2回答

温温酱

这是执行所需操作的例行程序:package mainimport ("fmt"; "regexp"; "os"; "strings";);func main () {&nbsp; &nbsp; reg, error := regexp.Compile ("B");&nbsp; &nbsp; if error != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf ("Compile failed: %s", error.String ());&nbsp; &nbsp; &nbsp; &nbsp; os.Exit (1);&nbsp; &nbsp; }&nbsp; &nbsp; output := string (reg.ReplaceAll (strings.Bytes ("ABBA"),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; strings.Bytes ("A")));&nbsp; &nbsp; fmt.Println (output);}

哈士奇WWW

这是一个小例子。您还可以在Regexp测试课中找到很好的例子package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "regexp"&nbsp; &nbsp; "strings")func main() {&nbsp; &nbsp; re, _ := regexp.Compile("e")&nbsp; &nbsp; input := "hello"&nbsp; &nbsp; replacement := "a"&nbsp; &nbsp; actual := string(re.ReplaceAll(strings.Bytes(input), strings.Bytes(replacement)))&nbsp; &nbsp; fmt.Printf("new pattern %s", actual)}
打开App,查看更多内容
随时随地看视频慕课网APP