How to remove excess spaces / spaces from a string in the Golang?

I was wondering how to remove:

  • All leading / trailing spaces or newlines, null characters, etc.
  • Any redundant spaces within the line (for example, "hello [space] [space] world" will be converted to "hello [space] world")

Is this possible with one Regex, with Unicode support for international space characters, etc.?

+11
source share
4 answers

, \s \p{Zs} Unicode Unicode. , , , ReplaceAllStringFunc ( , , ).

, :

  • ^[\s\p{Zs}]+|[\s\p{Zs}]+$ - /
  • [\s\p{Zs}]{2,} - 2

:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    input := "   Text   More here     "
    re_leadclose_whtsp := regexp.MustCompile('^[\s\p{Zs}]+|[\s\p{Zs}]+$')
    re_inside_whtsp := regexp.MustCompile('[\s\p{Zs}]{2,}')
    final := re_leadclose_whtsp.ReplaceAllString(input, "")
    final = re_inside_whtsp.ReplaceAllString(final, " ")
    fmt.Println(final)
}
+16

, strings, strings.Fields :

package main

import (
    "fmt"
    "strings"
)

func standardizeSpaces(s string) string {
    return strings.Join(strings.Fields(s), " ")
}

func main() {
    tests := []string{" Hello,   World  ! ", "Hello,\tWorld ! ", " \t\n\t Hello,\tWorld\n!\n\t"}
    for _, test := range tests {
        fmt.Println(standardizeSpaces(test))
    }
}
// "Hello, World !"
// "Hello, World !"
// "Hello, World !"
+42

strings.Fields () splits into any number of spaces, thus:

strings.Join(strings.Fields(strings.TrimSpace(s)), " ")
0
source

Use regexp for this.

func main() {
    data := []byte("   Hello,   World !   ")
    re := regexp.MustCompile("  +")
    replaced := re.ReplaceAll(bytes.TrimSpace(data), []byte(" "))
    fmt.Println(string(replaced))
    // Hello, World !
}

To also trim newlines and null characters, you can use the function bytes.Trim(src []byte, cutset string)insteadbytes.TrimSpace

-1
source

All Articles