drdot
drdot

Reputation: 3347

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

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?

Upvotes: 0

Views: 2012

Answers (2)

mkopriva
mkopriva

Reputation: 38233

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

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521289

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

Upvotes: 1

Related Questions