I need to split a string by a separator but don't want to split if the separator is prefixed by the escape string.
For example:
"This works\\ but it\\ isn't pretty."
with " "
as the separator and "\\"
as the escape string should produce the following: []string{"This", "works but", "it isn't", "pretty."}
I wrote the following code for it:
func SplitWithEscaping(s string, separator string, escapeString string) []string {
untreated := strings.Split(s, separator)
toReturn := make([]string, 0, len(untreated))
for i := 0; i < len(untreated); i++ {
next, ii := t(untreated, i, separator, escapeString)
i = ii - 1
toReturn = append(toReturn, strings.ReplaceAll(next, escapeString+separator, separator))
}
return toReturn
}
func t(stringSlice []string, i int, seperator, escapeString string) (string, int) {
if !strings.HasSuffix(stringSlice[i], escapeString) {
return stringSlice[i], i + 1
}
next, ii := t(stringSlice, i+1, seperator, escapeString)
return stringSlice[i] + seperator + next, ii
}
This is the playground link for my working code: https://play.golang.org/p/jfHFt9_vtE7
How can I make my code prettier but also more performant?