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

标签 regex go replace

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

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

}

最佳答案

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

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

关于regex - 如何使用 Regexp 包 ReplaceAll 函数替换 Go 中的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1738057/

相关文章:

javascript - 匹配开头不带点的数字

忽略第一个和最后一个字符的正则表达式

image - 如何使用Go编程语言读取彩色png文件并输出为灰度?

go - 如何解码 Golang Viper snake_case 值

css - 图像定位不起作用

jquery - 如果元素包含字符串则替换它

正则表达式匹配一个带有数字的单词

java - java中如何查找字符串中的空格分隔字符?

Golang 错误或 map 文字上的预期功能?

python - 替换字符串中的特定单词 (Python)