regex - 在 Go 中使用正则表达式拆分字符串

标签 regex go split

我正在尝试找到一种使用正则表达式而不是字符串来拆分字符串的好方法。谢谢

http://nsf.github.io/go/strings.html?f:Split !

最佳答案

您可以使用 regexp.Split 将字符串拆分为以正则表达式模式作为分隔符的字符串 slice 。

package main

import (
    "fmt"
    "regexp"
)

func main() {
    re := regexp.MustCompile("[0-9]+")
    txt := "Have9834a908123great10891819081day!"

    split := re.Split(txt, -1)
    set := []string{}

    for i := range split {
        set = append(set, split[i])
    }

    fmt.Println(set) // ["Have", "a", "great", "day!"]
}

关于regex - 在 Go 中使用正则表达式拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4466091/

相关文章:

php - 使用 PHP 正则表达式获取特定的 "<elm>..</elm>"?

sql - 存储简单正则表达式的高效方法

regex - ActionScript 使用\Q 来忽略特价。得到奇怪的结果

go - 在 golang 中为 ws 创建单元测试

templates - Go模板遍及结构的结构

python - 在特定索引处拆分字符串

python - 这条线在错误的地方 split

java - 正则表达式:星号重复运算符的所有格量词,即\d**

json - 如何解码json

javascript - 拆分文本以每 n 个字符添加一个新行,注意空格