英文:
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 (>= 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!
答案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 (
"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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论