Splitting a string on a list of strings in Go

huangapple go评论71阅读模式
英文:

Splitting a string on a list of strings in Go

问题

可以将字符串切割成多个子字符串,不仅限于一个字符串,还可以使用一个字符串切片。例如:

strings.Split("Dogs and Cats are Great", []string{"and", "are"})

这样就可以将字符串 "Dogs and Cats are Great" 按照 "and" 和 "are" 进行切割。

英文:

Is it possible to split not just on one string but also a slice of strings? I.e.

strings.Split("Dogs and Cats are Great", "and"))

But instead of using one string, a slice of strings as so:

strings.Split("Dogs and Cats are Great", []string{"and", "are"}))

答案1

得分: 5

你可以使用正则表达式:http://play.golang.org/p/vCRCv4rt7s

re := regexp.MustCompile(`and|are`)
fmt.Printf("%q\n", re.Split("Dogs and Cats are Great", -1))
英文:

You can use a regular expression: http://play.golang.org/p/vCRCv4rt7s

re := regexp.MustCompile(`and|are`)
fmt.Printf("%q\n", re.Split("Dogs and Cats are Great", -1))

huangapple
  • 本文由 发表于 2016年1月14日 00:07:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/34771452.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定