dongqing904999 2016-12-23 12:59
浏览 584

正则表达式类型的Golang SplitAfter

In golang strings.SplitAfter method split text after an special character into an slice, but I didn't find a way for Regexp type to split text after matches. Is there a way to do that?

Example :

var text string = "1.2.3.4.5.6.7.8.9"

res := strings.Split(text, ".")
fmt.Println(res) // print [1 2 3 4 5 6 7 8 9]

res = strings.SplitAfter(text, ".")
fmt.Println(res) // print [1. 2. 3. 4. 5. 6. 7. 8. 9]
  • 写回答

1条回答 默认 最新

  • du8980919 2016-12-25 23:10
    关注

    Regexp type itself does not have a method to do that exactly that but it's quite simple to write a function that implements what your asking based on Regexp functionality:

    func SplitAfter(s string, re *regexp.Regexp) []string {
        var (
            r []string
            p int
        )
        is := re.FindAllStringIndex(s, -1)
        if is == nil {
            return append(r, s)
        }
        for _, i := range is {
            r = append(r, s[p:i[1]])
            p = i[1]
        }
        return append(r, s[p:])
    }
    

    Here I left a program to play with it.

    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效