golang cuts irregular strings with multiple spaces

Cut strings according to spaces. If the spaces between strings are irregular and there are one or more spaces, an error will be reported if the string is intercepted according to one or two spaces. You can split the string according to regular rules. Example code as follows:

package main
​
import (
    "fmt"
    "regexp"
)
​
func main() {
    str := "hello     world   golang"
​
    // 使用正则表达式切割多个空格
    reg := regexp.MustCompile(`\s+`)
    result := reg.Split(str, -1)
​
    fmt.Println(result) // [hello world golang]
}

Use  regexp.MustCompile() a function to create a regular expression that matches multiple spaces ( \s+ meaning match at least one space character). Then, use  reg.Split() the method to cut the string, and the second parameter  -1 means to return all matching results.

The final output is  [hello world golang], which contains the cut string array

Guess you like

Origin blog.csdn.net/banzhuantuqiang/article/details/131473588