中学数学621094 views
Computer364642 views
高校日本史189759 views
LaTeX956652 views
高校国語785262 views
高校生物549563 views
数学講師2847003 views
中学英語808125 views
中学社会666920 views
高校物理158008 views
Help
Tools

English

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