高校化学2913383 views
小学算数1194618 views
りんご192546 views
教育148875 views
中学理科1626207 views
英語607877 views
ヒストリア284143 views
Computer365120 views
小学社会308636 views
高校物理158224 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