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

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

golang regexp ReplaceAllStrings with backreference doesn't quite work

问题

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

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

package main

import (
	"fmt"
	"regexp"
	"strings"
)

func main() {
	re := regexp.MustCompile(`\b([a-z])`)
	fmt.Println(re.ReplaceAllString("my test string", strings.ToUpper("$1")))
}

链接: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:

package main

import (
	"fmt"
	"regexp"
	"strings"
)

func main() {
	re := regexp.MustCompile(`\b([a-z])`)
	fmt.Println(re.ReplaceAllString("my test string", strings.ToUpper("$1")))
	
}

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

答案1

得分: 3

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

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

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

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

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

与下面的代码是一样的:

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

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

英文:

You should use ReplaceAllStringFunc, example:

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

See working [demo][1].

Your code doesn't work because:

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

is the same as:

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:

确定