英文:
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}]*`)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论