使用Golang的正则表达式可以找到一个字符串,并且只提取其中的子字符串。

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

golang regex to find a string but only extract the substring within it

问题

我有两个字符串,如下所示:

mystr = "xyz/10021abc/f123"
mystr2 = "abc/10021abd/c222"

我想提取出10021abc和10021abd。我尝试了以下正则表达式:

r = regexp.MustCompile(`(?:xyz\/|abc\/)(.+)\/`)

但是当我使用以下代码提取匹配项时:

fmt.Println(r.FindString(mystr))

它返回整个字符串。我应该如何修改我的正则表达式?

英文:

I have a two strings like this

mystr = "xyz/10021abc/f123"
mystr2 = "abc/10021abd/c222"

I want to extract 10021abc and 10021abd. I came up with

r = regexp.MustCompile(`(?:xyz\/|abc\/)(.+)\/`)

But when I want to extract the match using this:

fmt.Println(r.FindString(mystr))

It returns the entire string. How should I change my regex?

答案1

得分: 2

你可以使用FindStringSubmatch函数。

var re = regexp.MustCompile(`(?:xyz\/|abc\/)(.+)\/`)
var s1 = "xyz/10021abc/f123"
var s2 = "abc/10021abd/c222"

fmt.Println(re.FindStringSubmatch(s1)[1])
fmt.Println(re.FindStringSubmatch(s2)[1])

https://go.dev/play/p/C93DbfzVv3a

英文:

You can use FindStringSubmatch.

var re = regexp.MustCompile(`(?:xyz\/|abc\/)(.+)\/`)
var s1 = "xyz/10021abc/f123"
var s2 = "abc/10021abd/c222"

fmt.Println(re.FindStringSubmatch(s1)[1])
fmt.Println(re.FindStringSubmatch(s2)[1])

https://go.dev/play/p/C93DbfzVv3a

答案2

得分: 1

你可以在这里使用正则表达式替换:

var mystr = "xyz/10021abc/f123"
var re = regexp.MustCompile(`^.*?/|/.*$`)
var output = re.ReplaceAllString(mystr, "")
fmt.Println(output)  // 10021abc
英文:

You could use a regex replacement here:

var mystr = "xyz/10021abc/f123"
var re = regexp.MustCompile(`^.*?/|/.*$`)
var output = re.ReplaceAllString(mystr, "")
fmt.Println(output)  // 10021abc

huangapple
  • 本文由 发表于 2022年9月16日 14:44:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/73740901.html
匿名

发表评论

匿名网友

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

确定