Find numbers in string using Golang regexp

2020-08-16 16:34发布

I want to find all numbers in a string with the following code:

re:=regexp.MustCompile("[0-9]+")
fmt.Println(re.FindAllString("abc123def", 0))

I also tried adding delimiters to the regex, using a positive number as second parameter for FindAllString, using a numbers only string like "123" as first parameter...

But the output is always []

I seem to miss something about how regular expressions work in Go, but cannot wrap my head around it. Is [0-9]+ not a valid expression?

标签: regex go
1条回答
Bombasti
2楼-- · 2020-08-16 17:10

The problem is with your second integer argument. Quoting from the package doc of regex:

These routines take an extra integer argument, n; if n >= 0, the function returns at most n matches/submatches.

You pass 0 so at most 0 matches will be returned; that is: none (not really useful).

Try passing -1 to indicate you want all.

Example:

re := regexp.MustCompile("[0-9]+")
fmt.Println(re.FindAllString("abc123def987asdf", -1))

Output:

[123 987]

Try it on the Go Playground.

查看更多
登录 后发表回答