英文:
Escape a dollar sign in a regex replacement string
问题
我有一个函数,需要将"byte"替换为"$ball",但似乎无法正常工作。以下是程序片段。
fun main() {
str := []byte("$apple in a byte\n")
strReplace := "$ball"
re := regexp.MustCompile("byte")
final := re.ReplaceAll(str, []byte(strReplace))
ioutil.WriteFile("testfile.txt", final, 0744)
}
期望的输出在testfile.txt中:
$apple in a $ball
实际输出在testfile.txt中:
$apple in a
有没有成功获得所需输出的解决方案?
英文:
I have a function in which I need to replace "byte" with "$ball". This doesn't seem to work correctly.
Here is the program snippet.
fun main() {
str := []byte("$apple in a byte\n")
strReplace := "$ball"
re := regexp.MustCompile("byte")
final := re.ReplaceAll(str, []byte(strReplace))
ioutil.WriteFile("testfile.txt", final, 0744)
}
Expected Output in testfile.txt:
$apple in a $ball
Actual Output in testfile.txt:
$apple in a
Any solutions for successfully getting the desired output?
答案1
得分: 1
你使用的是$$
,这正是文档告诉你的。不过,你需要按照文档的指引一直追踪下去,才能找到最终的答案。
在ReplaceAll
的godoc部分(https://godoc.org/regexp#Regexp.ReplaceAll)告诉你:
> $符号的解释与Expand
中的解释相同
所以,在Expand
的部分末尾就有答案了。https://godoc.org/regexp#Regexp.Expand
>要在输出中插入一个字面上的$符号,请在模板中使用$$。
英文:
You use $$
which is exactly what the documentation tells you. You do have to follow the paper trail to get right down to the final word though.
The godoc section for ReplaceAll
(https://godoc.org/regexp#Regexp.ReplaceAll) tells you:
> $ signs are interpreted as in Expand
So reading the section for Expand
has the answer right at the end. https://godoc.org/regexp#Regexp.Expand
>To insert a literal $ in the output, use $$ in the template.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论