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.

    评论

报告相同问题?

悬赏问题

  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致