2010-12-16 22:41
浏览 1.3k


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!

图片转代码服务由CSDN问答提供 功能建议

我对Go真的很陌生,到目前为止一直很喜欢。 我正在尝试找到一种使用正则表达式而不是字符串来拆分字符串的好方法。 谢谢

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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • dongxu1668 2011-02-25 17:51

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

    解决 无用
    打赏 举报
  • dongraobei6719 2010-12-16 23:08

    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.!

    解决 无用
    打赏 举报
  • duanpi5733 2013-02-08 03:10

    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


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


    [a b c d]
    解决 无用
    打赏 举报
  • duanmei9980 2017-02-05 19:10

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

    解决 无用
    打赏 举报
  • douxitao8170 2018-07-05 16:12

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

    package main
    import (
    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!"]
    解决 无用
    打赏 举报

相关推荐 更多相似问题