dqwh26750 2009-11-15 16:42
浏览 65
已采纳

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

I am not familiar with C-like syntaxes and would like to write code to find & 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 code snippet from the Go documentation:

// 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条回答 默认 最新

  • dongpangfu6322 2009-11-15 17:17
    关注

    This is a routine to do what you want:

    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条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集