dpsx99068
2016-07-20 05:18
浏览 743
已采纳

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

I'm trying to convert CamelCase to snake_case using the regex I found here. Here's a snippet of the code I'm using:

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

The regex will match lCase. $1 here is l and $2 is Case, so using the replacement string "$1_$2" should result in camel_Case. Instead, it results in cameCase.

Changing the replacement string to "$1_" results in came. If I change it to "$1+$2", the result will be camel+Case as expected (see playground).

Right now, my workaround is to use "$1+$2" as the replacement string, and then using strings.Replace to change the plus sign to an underscore. Is this a bug or am I doing something wrong here?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试使用我发现的正则表达式将CamelCase转换为snake_case 此处。 这是我正在使用的代码段:</ p>

 中:=“ camelCase” 
var re1 = regexp.MustCompile(`(。)([AZ] [az]  +)`)
out:= re1.ReplaceAllString(in,“ $ 1_ $ 2”)
 </ code> </ pre> 
 
 

正则表达式将匹配 lCase </ code>。 $ 1 </ code>在这里是 l </ code>,而 $ 2 </ code>是 Case </ code>,因此使用替换字符串“ $ 1_ $ 2” </ code>应该会导致 camel_Case </ code>。 相反,它会导致 cameCase </ code>。 </ p>

将替换字符串更改为“ $ 1 _” </ code>会导致来</ code>。 如果我将其更改为“ $ 1 + $ 2” </ code>,结果将为预期的 camel + Case </ code>(看到游乐场)。</ p>

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

1条回答 默认 最新

相关推荐 更多相似问题