Split string using regular expression in Go

╄→гoц情女王★ 提交于 2019-12-04 02:59:35

问题


I'm really new to Go, and have been enjoying it so far. I'm trying to find a good way to split a string using a regular expression instead of a string. Thanks

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


回答1:


If you just want to split on certain characters, you can use strings.FieldsFunc, otherwise I'd go with regexp.FindAllString.




回答2:


I made a regex-split function based on the behavior of regex split function in java, c#, php.... It returns only an array of strings, without the index information.

func RegSplit(text string, delimeter string) []string {
    reg := regexp.MustCompile(delimeter)
    indexes := reg.FindAllStringIndex(text, -1)
    laststart := 0
    result := make([]string, len(indexes) + 1)
    for i, element := range indexes {
            result[i] = text[laststart:element[0]]
            laststart = element[1]
    }
    result[len(indexes)] = text[laststart:len(text)]
    return result
}

example:

fmt.Println(RegSplit("a1b22c333d", "[0-9]+"))

result:

[a b c d]



回答3:


The regexp.Split() function would be the best way to do this.




回答4:


You can use regexp.Split to split a string into a slice of strings with the regex pattern as the delimiter.

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!"]
}



回答5:


You should be able to create your own split function that loops over the results of RegExp.FindAllString, placing the intervening substrings into a new array.

http://nsf.github.com/go/regexp.html?m:Regexp.FindAllString!



来源:https://stackoverflow.com/questions/4466091/split-string-using-regular-expression-in-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!