Split a string on whitespace in Go?

Solution 1:

The strings package has a Fields method.

someString := "one    two   three four "

words := strings.Fields(someString)

fmt.Println(words, len(words)) // [one two three four] 4

DEMO: http://play.golang.org/p/et97S90cIH

From the docs:

func Fields(s string) []string

Fields splits the string s around each instance of one or more consecutive white space characters, returning an array of substrings of s or an empty list if s contains only white space.

Solution 2:

If you're using tip: regexp.Split

func (re *Regexp) Split(s string, n int) []string

Split slices s into substrings separated by the expression and returns a slice of the substrings between those expression matches.

The slice returned by this method consists of all the substrings of s not contained in the slice returned by FindAllString. When called on an expression that contains no metacharacters, it is equivalent to strings.SplitN.

Example:

s := regexp.MustCompile("a*").Split("abaabaccadaaae", 5)
// s: ["", "b", "b", "c", "cadaaae"]

The count determines the number of substrings to return:

n > 0: at most n substrings; the last substring will be the unsplit remainder.
n == 0: the result is nil (zero substrings)
n < 0: all substrings

Solution 3:

I came up with the following, but that seems a bit too verbose:

import "regexp"
r := regexp.MustCompile("[^\\s]+")
r.FindAllString("  word1   word2 word3   word4  ", -1)

which will evaluate to:

[]string{"word1", "word2", "word3", "word4"}

Is there a more compact or more idiomatic expression?