Escape a dollar sign in a regex replacement string

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

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.

huangapple
  • 本文由 发表于 2017年8月9日 00:19:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/45573392.html
匿名

发表评论

匿名网友

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

确定