Home > Software engineering >  Split data inside parenthesis to named groups using regex in golang
Split data inside parenthesis to named groups using regex in golang

Time:10-31

I have to formats of lines that I want to separate using regex and named groups. The 1st format is:

a (>= 1.1)

The 2nd format is:

b (>= 1.1, < 2.0)

I want to create groups that will have for each operator a matching version, and also to mark the letter outside the parenthesis.

For example:

n-> b
o1 -> >=
v1 -> 1.1
o2 -> <
v2 -> 2.0

I've tried and created the below regex:

(?P<n>\S ) *(\(((?P<o>[>=<~]?[>=<~])? (?P<v>\S ))*\))?\s*$

But I can't separate the text inside the parenthesis.

Please notice that in GO regex don't support look behind\ahead.

Is there a way to separate the content with the same regular expression?

Thanks!

CodePudding user response:

@blackgreen is right

package main

import (
    "fmt"
    "regexp"
)

func myRegx(s string) (n string, o []string, v []string) {
    regx := regexp.MustCompile(`(\S ) \(([>=<] )\s ([\d\.]*)(,\s ([>=<] )\s ([\d.] ))?\)`)
    b := regx.FindStringSubmatch(s)
    n = b[1]
    if len(b) < 4 {
        o = append(o, b[2])
        v = append(v, b[3])
    } else {
        o = append(o, b[2])
        v = append(v, b[3])
        o = append(o, b[5])
        v = append(v, b[6])
    }
    return n, o, v
}

func main() {
    n, o, v := myRegx("b (>= 1.1, < 2.0)")
    fmt.Printf("n: %v o:%v v:%v\n", n, o, v)
    n, o, v = myRegx("a (>= 1.1)")
    fmt.Printf("n: %v o:%v v:%v\n", n, o, v)
}

  • Related