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?
\d (digit) matches any single digit (same as [0-9] ). The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ). \s (space) matches any single whitespace (same as [ \t\n\r\f] , blank, tab, newline, carriage-return and form-feed).
In Go regexp, you are allowed to check whether the given string contains any match of the specified regular expression pattern with the help of MatchString() function. This function is defined under the regexp package, so for accessing this method you need to import the regexp package in your program.
The reason is regex deals with text only and not numbers, hence you have to take a little care while dealing with numbers and number ranges or numeric ranges in regex match, search, validate or replace operations.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With