使用ReplaceAllString和ToUpper不起作用

What I'm doing wrong? Why ToUpper isn't working?

package main

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

func main() {

    r := regexp.MustCompile("(\\w)(\\w+)")

    // Getting "sometext" instead of "SomeText"
    res := r.ReplaceAllString("some text", strings.ToUpper("$1") + "$2")

    fmt.Println(res)
}

You can't use $1 and $2 like that I'm afraid!

I think you are trying to turn "some text" into "SomeText".

Here is an alternative solution

package main

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

func main() {
    r := regexp.MustCompile(`\s*\w+\s*`)
    res := r.ReplaceAllStringFunc("some text", func(s string) string {
        return strings.Title(strings.TrimSpace(s))
    })

    fmt.Println(res)
}

strings.ToUpper("$1") doesn't appear like it's working because the input is not what you think it is. Let's break down your program into a more readable fashion to uncover what the issue is:

package main

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

func main() {

    r := regexp.MustCompile("(\\w)(\\w+)")

    upper := strings.ToUpper("$1")  // upper == upcase("$1") == "$1"

    res := r.ReplaceAllString("some text", upper + "$2") // passing in "$1 $2"

    fmt.Println(res)
}

As you can see, the $1 is not substituted yet when you call strings.ToUpper.

Unfortunately, you can't really use strings.ReplaceAllString to accomplish what you're trying to do, however, as Nick Craig-Wood mentioned in another answer, you can use strings.ReplaceAllStringFunc to accomplish the desired behavior.