我不熟悉类似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();
}
温温酱
哈士奇WWW