Split data inside parenthesis to named groups using regex in golang

huangapple go评论75阅读模式
英文:

Split data inside parenthesis to named groups using regex in golang

问题

我有两种格式的行,我想使用正则表达式和命名组来分隔。

第一种格式是:

a (>= 1.1)

第二种格式是:

b (>= 1.1, < 2.0)

我想创建一些组,每个操作符都有一个匹配的版本,并且标记括号外的字母。

例如:

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

我尝试了以下正则表达式:

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

但是我无法分隔括号内的文本。

请注意,在GO中,正则表达式不支持向前或向后查找。

有没有办法使用同一个正则表达式分隔内容?

谢谢!

英文:

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

a (&gt;= 1.1)

The 2nd format is:

b (&gt;= 1.1, &lt; 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-&gt; b
o1 -&gt; &gt;=
v1 -&gt; 1.1
o2 -&gt; &lt;
v2 -&gt; 2.0

I've tried and created the below regex:

(?P&lt;n&gt;\S+) *(\(((?P&lt;o&gt;[&gt;=&lt;~]?[&gt;=&lt;~])? (?P&lt;v&gt;\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!

答案1

得分: 0

@blackgreen 是正确的

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)
}
英文:

@blackgreen is right

package main

import (
	&quot;fmt&quot;
	&quot;regexp&quot;
)

func myRegx(s string) (n string, o []string, v []string) {
	regx := regexp.MustCompile(`(\S+) \(([&gt;=&lt;]+)\s+([\d\.]*)(,\s+([&gt;=&lt;]+)\s+([\d.]+))?\)`)
	b := regx.FindStringSubmatch(s)
	n = b[1]
	if len(b) &lt; 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(&quot;b (&gt;= 1.1, &lt; 2.0)&quot;)
	fmt.Printf(&quot;n: %v o:%v v:%v\n&quot;, n, o, v)
	n, o, v = myRegx(&quot;a (&gt;= 1.1)&quot;)
	fmt.Printf(&quot;n: %v o:%v v:%v\n&quot;, n, o, v)
}

huangapple
  • 本文由 发表于 2022年10月30日 22:23:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/74253836.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定