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