How to remove redundant spaces/whitespace from a string in Golang?

后端 未结 5 2078
借酒劲吻你
借酒劲吻你 2021-02-02 12:44

I was wondering how to remove:

  • All leading/trailing whitespace or new-line characters, null characters, etc.
  • Any redundant spaces within
5条回答
  •  名媛妹妹
    2021-02-02 13:25

    It seems that you might want to use both \s shorthand character class and \p{Zs} Unicode property to match Unicode spaces. However, both steps cannot be done with 1 regex replacement as you need two different replacements, and the ReplaceAllStringFunc only allows a whole match string as argument (I have no idea how to check which group matched).

    Thus, I suggest using two regexps:

    • ^[\s\p{Zs}]+|[\s\p{Zs}]+$ - to match all leading/trailing whitespace
    • [\s\p{Zs}]{2,} - to match 2 or more whitespace symbols inside a string

    Sample code:

    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)
    }
    

提交回复
热议问题