Treat numbers as word boundaries

This commit is contained in:
Ian Coleman 2017-11-29 11:52:26 +11:00
parent e1e131f0f2
commit 30c986a8fa
5 changed files with 21 additions and 0 deletions

View File

@ -6,6 +6,7 @@ import (
// Converts a string to CamelCase
func toCamelInitCase(s string, initCase bool) string {
s = addWordBoundariesToNumbers(s)
s = strings.Trim(s, " ")
n := ""
capNext := initCase
@ -13,6 +14,9 @@ func toCamelInitCase(s string, initCase bool) string {
if v >= 'A' && v <= 'Z' {
n += string(v)
}
if v >= '0' && v <= '9' {
n += string(v)
}
if v >= 'a' && v <= 'z' {
if capNext {
n += strings.ToUpper(string(v))

View File

@ -14,6 +14,7 @@ func TestToCamel(t *testing.T) {
[]string{ "many_many_words", "ManyManyWords" },
[]string{ "AnyKind of_string", "AnyKindOfString" },
[]string{ "odd-fix", "OddFix" },
[]string{ "numbers2And55with000", "Numbers2And55With000" },
}
for _, i := range cases {
in := i[0]

14
numbers.go Normal file
View File

@ -0,0 +1,14 @@
package strcase
import (
"regexp"
)
var numberSequence = regexp.MustCompile(`([a-zA-Z])(\d+)([a-zA-Z]?)`)
var numberReplacement = []byte(`$1 $2 $3`)
func addWordBoundariesToNumbers(s string) string {
b := []byte(s)
b = numberSequence.ReplaceAll(b, numberReplacement)
return string(b)
}

View File

@ -7,6 +7,7 @@ import (
// Converts a string to snake_case
func ToSnake(s string) string {
s = addWordBoundariesToNumbers(s)
s = strings.Trim(s, " ")
n := ""
for i, v := range s {

View File

@ -19,6 +19,7 @@ func TestToSnake(t *testing.T) {
[]string{ "ManyManyWords", "many_many_words" },
[]string{ "manyManyWords", "many_many_words" },
[]string{ "AnyKind of_string", "any_kind_of_string" },
[]string{ "numbers2and55with000", "numbers_2_and_55_with_000" },
}
for _, i := range cases {
in := i[0]