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

Time:09-16

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?

CodePudding user response:

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

CodePudding user response:

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

  • Related