📜  高朗 |拆分由指定表达式分隔的切片

📅  最后修改于: 2021-10-24 14:20:35             🧑  作者: Mango

正则表达式是定义搜索模式的字符序列。 Go 语言支持正则表达式。正则表达式用于从大文本(如日志、其他程序生成的输出等)中解析、过滤、验证和提取有意义的信息。
在 Go regexp 中,您可以借助Split()方法将切片拆分为由指定表达式分隔的子字符串。此方法返回这些表达式匹配之间的子字符串片段,计数表示要返回的子字符串数。这个方法是在regexp包下定义的,所以为了访问这个方法,你需要在你的程序中导入regexp包。

句法:

func (re *Regexp) Split(str string, m int) []string

在这里,如果m>0 ,那么它最多返回 m 个子串并且最后一个字符串子串不会分裂。如果m == 0 ,那么它将返回 nil。如果m<0 ,则它将返回所有子字符串。

示例 1:

// Go program to illustrate how to split a
// slice separated by the specified expression
package main
  
import (
    "fmt"
    "regexp"
)
  
// Main function
func main() {
  
    // Splitting the given slice which is
    // separated by the given expression
    // Using Split() method
    m1 := regexp.MustCompile(`e`)
  
    fmt.Println(m1.Split("GeeksforGeeks", -1))
    fmt.Println(m1.Split("GeeksforGeeks", 1))
    fmt.Println(m1.Split("GeeksforGeeks", 0))
    fmt.Println(m1.Split("GeeksforGeeks", 3))
    fmt.Println(m1.Split("GeeksforGeeks", 2))
    fmt.Println()
  
    m2 := regexp.MustCompile(`123`)
    fmt.Println(m2.Split("123Gee123ks123Geek123s", -2))
    fmt.Println(m2.Split("123Gee123ks123Geek123s", 3))
    fmt.Println(m2.Split("123Gee123ks123Geek123s", 0))
    fmt.Println(m2.Split("123Gee123ks123Geek123s", -1))
    fmt.Println(m2.Split("123Gee123ks123Geek123s", 1))
  
}

输出:

[G  ksforG  ks]
[GeeksforGeeks]
[]
[G  ksforGeeks]
[G eksforGeeks]

[ Gee ks Geek s]
[ Gee ks123Geek123s]
[]
[ Gee ks Geek s]
[123Gee123ks123Geek123s]

示例 2:

// Go program to illustrate how to split a
// slice separated by the specified expression
package main
  
import (
    "fmt"
    "regexp"
)
  
// Main function
func main() {
  
    // Creating and initializing a string
    // Using shorthand declaration
    s := "A vv regular vv  expression v is vv a sequence v"+
      " of vv characters v which define a vv search pattern."
  
    // Splitting the given slice which is
    // separated by the given expression
    // Using Split() method
    m := regexp.MustCompile(`v`)
    res1 := m.Split(s, -1)
    fmt.Println(res1)
  
    res2 := m.Split(s, 1)
    fmt.Println(res2)
  
    res3 := m.Split(s, -0)
    fmt.Println(res3)
  
    res4 := m.Split(s, -4)
    fmt.Println(res4)
  
}

输出:

[A    regular     expression   is    a sequence   of    characters   which define a    search pattern.]
[A vv regular vv  expression v is vv a sequence v of vv characters v which define a vv search pattern.]
[]
[A    regular     expression   is    a sequence   of    characters   which define a    search pattern.]