0

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 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

9 Comments

This program crash when there is no match
Of course it does. Any Go slice index expression will crash if there isn't enough elements in the slice. The standard approach is to check the slice's length before indexing. But that was not your question.
I already know how to do this. My Q is how to change the regex
It is a regex skill Q rather than a go programming Q if that makes sense ;)
I am happy to take this answer if you think updating regex to just match the substring I need is too hard
|
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.