3

Is it possible to split not just on one string but also a slice of strings? I.e.

strings.Split("Dogs and Cats are Great", "and"))

But instead of using one string, a slice of strings as so:

strings.Split("Dogs and Cats are Great", []string{"and", "are"}))

1 Answer 1

5

You can use a regular expression: http://play.golang.org/p/vCRCv4rt7s

re := regexp.MustCompile(`and|are`)
fmt.Printf("%q\n", re.Split("Dogs and Cats are Great", -1))
Sign up to request clarification or add additional context in comments.

5 Comments

This seems like an elegant solution. I am wondering, is there a way to split before the word rather than replacing it on the split?
@JamesMilner: Please show what you mean by "split before the word".
I.e. return "Dogs", "and Cats", "are Great" rather than "Dogs", "Cats", "Great"
@JamesMilner: I would find the indexes of the matches (using something like FindAllStringIndex), and slice the string based on that.
I think that's the best solution. Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.