英文:
Using ReplaceAllString and ToUpper not Working
问题
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)
}
英文:
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)
}
答案1
得分: 2
你不能像那样使用$1
和$2
,我很抱歉!
我想你正在尝试将“some text”转换为“SomeText”。
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)
}
英文:
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)
}
答案2
得分: 0
strings.ToUpper("$1")
看起来好像没有起作用,因为输入不是你想的那样。让我们将你的程序分解成更可读的方式,以找出问题所在:
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)
}
如你所见,当你调用 strings.ToUpper
时,$1
还没有被替换。
不幸的是,你不能真正使用 strings.ReplaceAllString
来实现你想要的效果,然而,正如 Nick Craig-Wood 在另一个答案中提到的,你可以使用 strings.ReplaceAllStringFunc
来实现所需的行为。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论