我不熟悉類C語法,並且想編寫代碼來找到&替換,例如,在源字符串中替換所有'A'到'B',用Regexp包替換AllAll或ReplaceAllString函數說'ABBA'?如何設置Regexp,src和repl類型?下面是的replaceAll code snippet從轉到文檔:如何使用Regexp包的ReplaceAll函數替換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();
}
我怎麼能處理2周更換一次:A-> B,B-> A,所以ABBA變成BAAB在1步? – user211499 2009-11-16 21:18:12
你爲什麼問我,而不是你接受答案的人? – 2009-11-17 04:48:22
拍,我在這裏是新手,甚至不知道我只能接受1個答案,並接受了兩個答案,因爲我嘗試了他們,他們的工作。 – user211499 2009-11-17 10:12:42