Trailing Whitespace (Per Line) in GO
Match trailing spaces and tabs at the end of each line — the regex linters use to flag dirty whitespace.
Try it in the GO tester →Pattern
regexGO
[ \t]+$ (flags: gm)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(?m)[ \t]+$`)
input := `good line\nbad line \nfine`
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
[ \t]+ matches one or more space or tab characters. $ with the m (multiline) flag anchors to the end of EACH line, not the whole string. The g flag iterates so a multi-line string surfaces every offending line. Pair with `replace(re, '')` to strip.
Examples
Input
good line\nbad line \nfineMatches
Input
tab here\tand more\t\tMatches
\t\t
Input
no trailing spaceNo match
—