Find numbers in string using Golang regexp

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

Find numbers in string using Golang regexp

问题

我想使用以下代码在字符串中找到所有的数字:

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

我还尝试在正则表达式中添加分隔符,将正整数作为FindAllString的第二个参数,将只包含数字的字符串如"123"作为第一个参数...

但输出始终为[]

我似乎对Go中正则表达式的工作原理有所遗漏,但无法理解。[0-9]+不是一个有效的表达式吗?

英文:

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?

答案1

得分: 47

问题出在你的第二个整数参数上。引用regex包的文档:

> 这些函数接受一个额外的整数参数n;如果n >= 0,函数最多返回n个匹配/子匹配。

你传递了0,所以最多返回0个匹配;也就是说:没有(实际上没有用处)。

尝试传递-1来表示你想要全部匹配。

示例:

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

输出:

[123 987]

Go Playground上试一试。

英文:

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.

答案2

得分: 0

@icza的答案对于获取正数是完美的,但是,如果你有一个包含负数的字符串,像下面这样:

"abc-123def987asdf"

并且你期望的输出是:

[-123 987]

请使用以下正则表达式替换正则表达式:

re := regexp.MustCompile(`[-]?\d[\d,]*[\.]?[\d{2}]*`)
英文:

@icza answer is perfect for fetching positive numbers but, if you have a string which contains negative numbers also like below

"abc-123def987asdf"

and you are expecting output like below

[-123 987]

replace regex expression with below

re := regexp.MustCompile(`[-]?\d[\d,]*[\.]?[\d{2}]*`)

huangapple
  • 本文由 发表于 2015年10月7日 16:21:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/32987215.html
匿名

发表评论

匿名网友

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

确定