Josh
11 Jun 2025

Go regex basic: Check if a string has only numbers

Here is the basic Go example of checking a string matches only numbers.

package main

import (
	"fmt"
	"regexp"
)


func main() {
	re := regexp.MustCompile(`^\d+$`)

	tests := []string{"12345", "abc123", "123abc", "007", "", " 123", "123 "}

	for _, str := range tests {
		if re.MatchString(str) {
			fmt.Printf("%q is all digits\n", str)

		} else {
			fmt.Printf("%q is NOT all digits\n", str)
		}
	}
}
"12345" is all digits
"abc123" is NOT all digits
"123abc" is NOT all digits
"007" is all digits
"" is NOT all digits
" 123" is NOT all digits
"123 " is NOT all digits