数学講師2922256 views
英語618759 views
小学社会311845 views
小学理科722400 views
中学英語814664 views
小学算数1204917 views
教育150285 views
高校化学2936058 views
Computer370547 views
ヒストリア296572 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