亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用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 關注
  • 385 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號