英文:
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: ")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论