简体   繁体   English

使用 Golang regexp 在字符串中查找数字

[英]Find numbers in string using Golang regexp

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...我还尝试向正则表达式添加分隔符,使用正数作为FindAllString第二个参数,使用像“123”这样的数字字符串作为第一个参数......

But the output is always []但输出总是[]

I seem to miss something about how regular expressions work in Go, but cannot wrap my head around it.我似乎错过了关于 Go 中正则表达式如何工作的一些东西,但我无法理解它。 Is [0-9]+ not a valid expression? [0-9]+不是有效的表达式吗?

The problem is with your second integer argument. 问题在于你的第二个整数参数。 Quoting from the package doc of regex : 引用regex的包文档:

These routines take an extra integer argument, n; 这些例程采用额外的整数参数n; if n >= 0, the function returns at most n matches/submatches. 如果n> = 0,则该函数最多返回n个匹配/子匹配。

You pass 0 so at most 0 matches will be returned; 你传递0所以最多返回0个匹配; that is: none (not really useful). 那就是: 没有 (不是很有用)。

Try passing -1 to indicate you want all. 尝试传递-1表示你想要所有。

Example: 例:

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

Output: 输出:

[123 987]

Try it on the Go Playground . Go Playground尝试一下。

@icza answer is perfect for fetching positive numbers but, if you have a string which contains negative numbers also like below @icza 答案非常适合获取正数,但是,如果您有一个包含负数的字符串,也如下所示

"abc-123def987asdf"

and you are expecting output like below你期待像下面这样的输出

[-123 987]

replace regex expression with below用下面的替换正则表达式

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM