当使用bytes.replace时,是否有一种使用通配符的方法?

huangapple go评论87阅读模式
英文:

When using bytes.replace is there a way to use wildcards?

问题

我正在使用Go编程,并读取一个文本文件,然后替换其中的多个内容,以将代码从一种语言转换为Go语言以便能够运行。我遇到的问题是,当尝试替换像Println语句这样的内容时,我无法在语句的末尾加上括号,除非对我正在转换的代码非常具体。有没有办法像这样使用代码?

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

并且能够在代码行的末尾只放置一个括号?

英文:

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?

答案1

得分: 2

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

英文:
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: ")

huangapple
  • 本文由 发表于 2012年12月10日 13:45:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/13795662.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定