Golang的regexp包是否与其他语言解析正则表达式的方式不同?

huangapple go评论78阅读模式
英文:

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 [^,].

huangapple
  • 本文由 发表于 2021年6月11日 06:03:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/67928958.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定