Remove all duplicate whitespace
yourbasic.org/golang
space := regexp.MustCompile(`\s+`)
s := space.ReplaceAllString("Hello \t \n world!", " ")
fmt.Printf("%q", s) // "Hello world!"
\s+
is a regular expression:
- the character class
\s
matches a space, tab, new line, carriage return or form feed, - and
+
says “one or more of those”.
In other words, the code will replace each whitespace substring with a single space character.
Trim leading and trailing space
To trim leading and trailing whitespace, use the strings.TrimSpace
function.
Further reading
Regular expressions
is a gentle introduction to the regexp
package with cheat sheet
and plenty of examples.