'Split a string on whitespace in Go?

Given an input string such as " word1 word2 word3 word4 ", what would be the best approach to split this as an array of strings in Go? Note that there can be any number of spaces or unicode-spacing characters between each word.

In Java I would just use someString.trim().split("\\s+").

(Note: possible duplicate Split string using regular expression in Go doesn't give any good quality answer. Please provide an actual example, not just a link to the regexp or strings packages reference.)



Solution 1:[1]

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 2:[2]

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?

Solution 3:[3]

You can use package strings function split strings.Split(someString, " ")

strings.Split

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 zzzz
Solution 2 ralfoide
Solution 3