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?