为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
慕森王 2021-04-08 10:15:16
我不熟悉类似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();}
查看完整描述

2 回答

?
温温酱

TA贡献1752条经验 获得超4个赞

这是执行所需操作的例行程序:


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

}


查看完整回答
反对 回复 2021-04-26
?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

这是一个小例子。您还可以在Regexp测试课中找到很好的例子


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)

}


查看完整回答
反对 回复 2021-04-26
  • 2 回答
  • 0 关注
  • 313 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信