如何更换使用正则表达式包的replaceAll功能转到一个人物?

我不熟悉的类C语法,并想编写代码来查找和替换,比方说,所有“A公司以'B在源字符串,说”利群“的正则表达式包的replaceAll或ReplaceAllString的功能呢? 我如何设置型正则表达式,src和REPL? 下面是从转到文档中的replaceAll代码片段:

//返回的replaceAll的src中所有匹配的正则表达式//已被替换为repl的副本。 不支持提供了用于替换文本表达式//(例如:\ 1或$ 1)。 FUNC(RE *正则表达式)的replaceAll(SRC,REPL []字节)[]字节{lastMatchEnd:= 0; //最近一次比赛searchPos的结束位置:= 0; //位置,我们接下来查找匹配BUF:=新(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(); // 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);
}

这里是一个小例子。 你也可以在他正则表达式测试类很好的例子

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 patern %s",actual);
}

分类:正则表达式 时间:2012-08-11 人气:0
本文关键词: 正则表达式,替换,去
分享到:

相关文章

Copyright (C) 55228885.com, All Rights Reserved.

55228885 版权所有 京ICP备15002868号

processed in 0.857 (s). 10 q(s)