gpt4 book ai didi

Golang regexp.ReplaceAllString 忽略替换字符串 "$X_"

转载 作者:IT王子 更新时间:2023-10-29 02:04:13 25 4
gpt4 key购买 nike

我正在尝试使用我找到的正则表达式将 CamelCase 转换为 snake_case here .这是我正在使用的代码片段:

in := "camelCase"
var re1 = regexp.MustCompile(`(.)([A-Z][a-z]+)`)
out := re1.ReplaceAllString(in, "$1_$2")

正则表达式将匹配 lCase$1这里是l$2Case,所以使用替换字符串"$1_$2" 应该导致 camel_Case。相反,它会导致 cameCase

将替换字符串更改为 "$1_" 会导致 came。如果我将其更改为 "$1+$2",结果将是 camel+Case,如预期的那样 (see playground)。

现在,我的解决方法是使用 "$1+$2" 作为替换字符串,然后使用 strings.Replace 将加号更改为下划线。这是错误还是我在这里做错了什么?

最佳答案

解决方法是使用 ${1}_$2(或 ${1}_${2} 实现对称)。

根据 https://golang.org/pkg/regexp/#Regexp.Expand (我的重点):

In the template, a variable is denoted by a substring of the form $name or ${name}, where name is a non-empty sequence of letters, digits, and underscores.

...

In the $name form, name is taken to be as long as possible: $1x is equivalent to ${1x}, not ${1}x, and, $10 is equivalent to ${10}, not ${1}0.

所以在 $1_$2 中,您实际上是在寻找一个名为 1_ 的组,然后是另一个名为 2 的组,然后将它们放在一起.

至于为什么使用 $1_$2(或 $foo$2)导致“cameCase”,同一文档说:

A reference to an out of range or unmatched index or a name that is not present in the regular expression is replaced with an empty slice.

因此替换为 "$1_$2" 等同于仅替换为 "$2"

关于Golang regexp.ReplaceAllString 忽略替换字符串 "$X_",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38472840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com