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