Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find numbers in string using Golang regexp

Tags:

regex

go

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?

like image 489
Fabian Schmengler Avatar asked Oct 07 '15 08:10

Fabian Schmengler


People also ask

How do you find digits in regex?

\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).

How do you check if a string matches a regex in Golang?

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.

Does regex work on numbers?

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.


1 Answers

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.

like image 134
icza Avatar answered Oct 03 '22 05:10

icza