Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update snake_case regex #59

Merged
merged 2 commits into from
Jun 5, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 1 addition & 5 deletions tooling/internal/formatting/formatting.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,7 @@ func ToPascalCase(s string) string {
return b.String()
}

// Copied from the from the VSCode "transform to snake case" command implementation.
// Note that their implementation has since been changed to use two regexes instead of using
// lookbehinds and lookaheads, but the implementation here is actually about two orders of magnitude faster.
// Note that in order to use lookbehinds, we need to use the regexp2 package.
var snakeCaseRegex = regexp2.MustCompile(`(?<=\p{Ll})(\p{Lu})|(?<!\b|_)(\p{Lu})(?=\p{Ll})`, regexp2.ExplicitCapture)
var snakeCaseRegex = regexp2.MustCompile(`((?<=\p{Ll})(\p{Lu}))|(?<!(\b|_)\p{Ll})((?<=\p{Ll})(\d))|(?<!\b|_)(\p{Lu})(?=\p{Ll})`, regexp2.ExplicitCapture)

func ToSnakeCase(str string) string {
s, err := snakeCaseRegex.Replace(str, `_$&`, -1, -1)
Expand Down
11 changes: 10 additions & 1 deletion tooling/internal/formatting/formatting_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,18 @@ func TestPascalOrCamelToSnakeCase(t *testing.T) {
{"Capital_Snake_Case", "capital_snake_case"},
{"YAML", "yaml"},
{"YAML2", "yaml2"},
{"yaml2Spec", "yaml2_spec"},
{"yaml2Spec", "yaml_2_spec"},
{"YAML2Spec", "yaml2_spec"},
{"YAML42Spec", "yaml42_spec"},
{"Super42", "super_42"},
{"Super42car", "super_42car"},
{"Super42Car", "super_42_car"},
{"myM1Processor", "my_m1_processor"},
{"myM1", "my_m1"},
{"m1", "m1"},
{"myMP3", "my_mp3"},
{"snake3C3ase", "snake_3c3ase"},
{"kspaceEncodeStep1", "kspace_encode_step_1"},
}
for _, tt := range tests {
t.Run(tt.intput, func(t *testing.T) {
Expand Down