Go (RE2)

Whitespace Trim (Leading & Trailing) in GO

Match leading and/or trailing whitespace on a string — the regex equivalent of .trim().

Try it in the GO tester →

Pattern

regexGO
^\s+|\s+$   (flags: g)

Go (RE2) code

goGo
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`^\s+|\s+$`)
	input := `  hello world  `
	for _, match := range re.FindAllString(input, -1) {
		fmt.Println(match)
	}
}

Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.

How the pattern works

^\s+ matches one or more whitespace characters at the start of the string. \s+$ matches one or more whitespace characters at the end. The alternation | with the g flag allows replacing both in a single pass.

Examples

Input

hello world

Matches

Input

tabbed

Matches

Input

no padding

No match

Same pattern, other engines

← Back to Whitespace Trim (Leading & Trailing) overview (all engines)