drqefnd544707688
2012-12-10 05:45
浏览 70
已采纳

使用bytes.replace时是否可以使用通配符?

I am programming in Go and I read a text file in and I replace multiple things on it to translate the code from one language to Go to be able to run. The problem I am having is that when trying to replace things like Println statements I cannot get a parenthesis on the end of the statement without being really specific to the code I am converting. Is there a way to use the code like this?

src = bytes.Replace(src, []byte("Insert"), []byte("Println(" * ")"), -1)

and have the ability to just put a parenthesis at the end of the line of code?

图片转代码服务由CSDN问答提供 功能建议

我正在用Go编程,我在其中读取了一个文本文件,然后替换了其中的多处内容以翻译代码 一种语言可以运行。 我遇到的问题是,当尝试替换诸如Println语句之类的内容时,如果不真正特定于要转换的代码,则无法在语句末尾加上括号。 有没有办法使用这样的代码?

  src = bytes.Replace(src,[] byte(“ Insert”),[] byte(“ Println(” *“)”),-1)
    
 
 

并能够在代码行的末尾加上括号?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • drf97973 2012-12-10 06:50
    已采纳
    package main
    
    import (
            "fmt"
            "regexp"
    )
    
    func main() {
            src := []byte(`
    Write(1, 3, "foo", 3*qux(42));
    WriteLn("Enter bar: ");
    `)
            re := regexp.MustCompile(`Write\((.*)\);`)
            re2 := regexp.MustCompile(`WriteLn\((.*)\);`)
            src = re.ReplaceAll(src, []byte(`Print($1)`))
            src = re2.ReplaceAll(src, []byte(`PrintLn($1)`))
            fmt.Printf("%s", src)
    }
    

    (Alse here)


    Output:

    Print(1, 3, "foo", 3*qux(42))
    PrintLn("Enter bar: ")
    
    点赞 评论

相关推荐 更多相似问题