【问题标题】:How do you replace a character in Go using the Regexp package ReplaceAll function?如何使用 Regexp 包 ReplaceAll 函数替换 Go 中的字符?
【发布时间】:2010-12-16 19:41:39
【问题描述】:

我不熟悉类似 C 的语法,想编写代码来查找和替换源字符串中的所有“A”到“B”,例如使用 Regexp 包 ReplaceAll 或 ReplaceAllString 函数的“ABBA”?如何设置类型 Regexp、src 和 repl?这是 Go 文档中的 ReplaceAll code snippet

// ReplaceAll 返回 src 的副本,其中所有匹配正则表达式
// 已经被repl替换了。不支持表达式
//(例如 \1 或 $1)在替换文本中。
func (re *Regexp) ReplaceAll(src, repl []byte) []byte {
    最后匹配结束:= 0; // 最近匹配的结束位置
    搜索位置:= 0; // 我们下一次寻找匹配的位置
    buf := new(bytes.Buffer);
    对于 searchPos     // 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();

}

【问题讨论】:

    标签: regex go replace


    【解决方案1】:

    这是做你想做的事的例行公事:

    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);
    }
    

    【讨论】:

    • 我怎样才能一次处理2个替换:A->B,B->A,所以ABBA一步变成BAAB?
    • 你为什么问我而不是你接受答案的那个人?
    • 拍摄,我在这里太菜鸟了,我什至不知道我只能接受其中的一个答案,并且在我尝试了它们并且它们工作时都接受了两个答案。
    • 哦,好的。 Go 的正则表达式非常原始,没有简单的方法来做你想做的事(交换 A 和 B),所以你必须做三个单独的交换(A->X,B->A,X->B)完成这项工作。
    • strings.Bytes 从 go1.7 开始似乎不起作用。我不得不使用实际的 := string(re.ReplaceAll([]byte("ABBA"), []byte("A")))。以防有人在 2017 年之后偶然发现这个答案:)
    【解决方案2】:

    这是一个小例子。你也可以在他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)
    }
    

    【讨论】:

    • string () 是我需要的。
    • strings.Bytes 从 go1.7 开始似乎不起作用。我不得不使用actual := string(re.ReplaceAll([]byte(input), []byte(replacement)))
    猜你喜欢
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    • 1970-01-01
    相关资源
    最近更新 更多