golang的regexp.ReplaceAllString函数使用反向引用时似乎不太起作用。

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

golang regexp ReplaceAllStrings with backreference doesn't quite work

问题

尝试将单词的每个字母的首字母大写。我知道有strings.Title函数,但对我的需求来说太不准确了。

我不确定为什么这段代码不起作用:

  1. package main
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strings"
  6. )
  7. func main() {
  8. re := regexp.MustCompile(`\b([a-z])`)
  9. fmt.Println(re.ReplaceAllString("my test string", strings.ToUpper("$1")))
  10. }

链接:https://play.golang.org/p/C-8QG1FrOi

英文:

Trying to capitalize each letter at begin of the word. I know that there is strings.Title, but that is too imprecise for my needs.

I am not sure why this does not work:

  1. package main
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strings"
  6. )
  7. func main() {
  8. re := regexp.MustCompile(`\b([a-z])`)
  9. fmt.Println(re.ReplaceAllString("my test string", strings.ToUpper("$1")))
  10. }

https://play.golang.org/p/C-8QG1FrOi

答案1

得分: 3

你应该使用ReplaceAllStringFunc,示例代码如下:

  1. re.ReplaceAllStringFunc("my test string", func(s string) string {
  2. return strings.ToUpper(s)
  3. })

可以查看这个[演示][1]来了解更多。

你的代码不起作用是因为:

  1. re.ReplaceAllString("my test string", strings.ToUpper("$1"))

与下面的代码是一样的:

  1. re.ReplaceAllString("my test string", "$1")

因为$1的大写仍然是$1

英文:

You should use ReplaceAllStringFunc, example:

  1. re.ReplaceAllStringFunc("my test string", func(s string) string {
  2. return strings.ToUpper(s)})

See working [demo][1].

Your code doesn't work because:

  1. re.ReplaceAllString("my test string", strings.ToUpper("$1"))

is the same as:

  1. re.ReplaceAllString("my test string", "$1")

since the upper case of $1 is still $1.
[1]: https://play.golang.org/p/Oil1S9-diy

huangapple
  • 本文由 发表于 2015年7月28日 22:53:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/31679929.html
匿名

发表评论

匿名网友

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

确定