regexgoregex-group

golang regex split string based on keywords


this is my string like findstudentbyid Now I would split based on keywords like find word before find word and after by and by, id.

So golang regex pattern is `(?i)(^find{1})(\w+)(by{1})(\w+)`

I am trying split this keyword findstudentbyid but I have an issue and I can't find an exact result which I am finding. my expected output is [find student by id] or

find
student
by
id

but I am unable to do this. I did try this golang code

package main

import (
    "fmt"
    "regexp"
)

func main() {

    txt := "findstudentbyid"
    re := regexp.MustCompile(`(?i)(^find{1})(\w+)(by{1})(\w+)`)
    split := re.Split(txt, -1)
    set := []string{}
    for i := range split {
        set = append(set, split[i])
    }

    fmt.Println(set)
}

Solution

  • I don't think Regexp.Split() is the solution for your case, according to the documentation:

    The slice returned by this method consists of all the substrings of s not contained in the slice returned by FindAllString.

    I guess the thing you need is finding the submatches ( like find, student, by and id ):

    Submatch 0 is the match of the entire expression, submatch 1 is the match of the first parenthesized subexpression, and so on.

    So you can use the Regexp.FindStringSubmatch() like this:

    fmt.Println("result: ", re.FindStringSubmatch(txt))
    
    result: [findstudentbyid find student by id]
    

    I also think that you can simplify your regex, but don't forget to put it into parentheses to handle the submatches, like the one that is pointed in the comments:

    re := regexp.MustCompile(`(find)(.+)(by)(.+)`)