Skip to content

Instantly share code, notes, and snippets.

@rodkranz
Last active October 29, 2018 14:56
Show Gist options
  • Save rodkranz/c92f10fc0a3ea38aa3416be2b1429e12 to your computer and use it in GitHub Desktop.
Save rodkranz/c92f10fc0a3ea38aa3416be2b1429e12 to your computer and use it in GitHub Desktop.
cut slice of text between start text and end text.
func CutBetweenText(s, start, end string) (string, bool) {
if !strings.HasPrefix(s, start) || !strings.HasSuffix(s, end) {
return "", false
}
if len(s) <= (len(start) + len(end)) {
return "", false
}
return s[len(start):][0 : len(s[len(start):])-len(end)], true
}
func TestCutBetweenText(t *testing.T) {
tests := []struct {
InputString string
InputStartString string
InputEndString string
ExpectedString string
ExpectedBool bool
}{
{
InputString: "Advert with uuid: a992ed90-6e24-4d60-b21c-d5775eb282e1 already exists",
InputStartString: "Advert with uuid: ",
InputEndString: " already exists",
ExpectedString: "a992ed90-6e24-4d60-b21c-d5775eb282e1",
ExpectedBool: true,
},
{
InputString: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
InputStartString: "Lorem ipsum ",
InputEndString: ", consectetur adipiscing elit.",
ExpectedString: "dolor sit amet",
ExpectedBool: true,
},
{
InputString: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
InputStartString: "Bananas",
InputEndString: "Amet",
ExpectedString: "",
ExpectedBool: false,
},
{
InputString: "",
InputStartString: "",
InputEndString: "",
ExpectedString: "",
ExpectedBool: false,
},
{
InputString: "",
InputStartString: "Lorem",
InputEndString: "Ipsum",
ExpectedString: "",
ExpectedBool: false,
},
{
InputString: "Lorem ipsum dolor",
InputStartString: "",
InputEndString: "",
ExpectedString: "Lorem ipsum dolor",
ExpectedBool: true,
},
}
for i, test := range tests {
t.Run(fmt.Sprintf("test-%d", i), func(t *testing.T) {
actualString, actualBool := CutBetweenText(test.InputString, test.InputStartString, test.InputEndString)
if actualBool != test.ExpectedBool {
t.Errorf("expected return bool [%t], but got bool [%t]", test.ExpectedBool, actualBool)
}
if actualString != test.ExpectedString {
t.Errorf("expected return string [%s], but got string [%s]", test.ExpectedString, actualString)
}
})
}
}
func BenchmarkCutBetweenText(b *testing.B) {
for i := 0; i < b.N; i++ {
CutBetweenText("Lorem ipsum dolor sit amet", "Lorem ipsum ", " dolor sit amet")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment