英文:
Does the Golang's regexp package parse regex differently than others?
问题
Golang在解析正则表达式时表现不如预期。我已经在正则表达式测试器上测试了我的正则表达式,它似乎按预期工作。以下是我的代码:
func main() {
tags := regexp.MustCompile(`[^,\s][^\,]*[^,\s]`).Split("foo, bar, baz", -1)
fmt.Println(tags)
}
在我的本地环境和 playground 中,Golang 返回的结果是 [ , , ],而预期的结果应该是 ["foo", "bar", "baz"]。
英文:
Golang isn't behaving as expected when parsing regex. I've tested my reg phrase on regextester and it seems to be working as expected. Here's my code:
func main() {
tags := regexp.MustCompile(`[^,\s][^\,]*[^,\s]`).Split("foo, bar, baz", -1)
fmt.Println(tags)
}
Golang, in both my local environemnt and the playground, returns [ , , ] where it should return ["foo", "bar", "baz"]
答案1
得分: 4
你需要使用FindAllString
来提取匹配项:
tags := regexp.MustCompile(`[^,\s][^,]*[^,\s]`).FindAllString("foo, bar, baz", -1)
可以参考Go playground。
请注意,在正则表达式中,你不需要转义逗号,[^\,]
可以更简洁地写为[^,]
。
英文:
You need to extract the matches with FindAllString
:
tags := regexp.MustCompile(`[^,\s][^,]*[^,\s]`).FindAllString("foo, bar, baz", -1)
See the Go playground.
Note you do not need to escape a comma anywhere in the regex, [^\,]
is more succintly written as [^,]
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论