Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions stringutil/camel_to_snake_case.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@ import (
"strings"
)

var upperCase = regexp.MustCompile(`([A-Z]+)`)
var upperCaseRegexps = []*regexp.Regexp{
regexp.MustCompile(`([A-Z][a-z]+)`),
regexp.MustCompile(`([A-Z]+)`),
}

func CamelToSnakeCase(s string) string {
s = upperCase.ReplaceAllString(s, `_$1`)
s = strings.TrimPrefix(s, "_")
for _, re := range upperCaseRegexps {
s = re.ReplaceAllStringFunc(s, func(s string) string { return "_" + strings.ToLower(s) })
}

return strings.ToLower(s)
return strings.ToLower(strings.TrimPrefix(s, "_"))
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Regex Overlap Causes Double Underscore

The implementation introduces double underscores when an acronym is followed by a capitalized word. When the second regex ([A-Z]+) matches a sequence of uppercase letters that already has an underscore prefix from the first pass, it adds another underscore. For example, "WithAcronymLikeURL" becomes "with_acronym_like__url" instead of the expected "with_acronym_like_url" due to the double underscore before "url". The test case will fail because the actual output doesn't match the expected output.

Fix in Cursor Fix in Web

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

say what? 🫨

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bot is tired it seems :suspect:

}
2 changes: 2 additions & 0 deletions stringutil/camel_to_snake_case_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ func TestCamelToSnakeCase(t *testing.T) {
{"Camel", "camel"},
{"VeryVeryLongCamelCase", "very_very_long_camel_case"},
{"WithAcronymLikeURL", "with_acronym_like_url"},
{"CRMFetcher", "crm_fetcher"},
{"A0", "a0"},
} {
if out := CamelToSnakeCase(tt.in); tt.out != out {
t.Errorf("CamelToSnakeCase(%q) = %q wanted: %q", tt.in, out, tt.out)
Expand Down
Loading