OneBite.Dev - Coding blog in a bite size

check if a string contains only numbers in Go

Code snippet on how to check if a string contains only numbers in Go

package main

import (
	"fmt"
	"regexp"
)

func main() {
	str := "123456"

	r, err := regexp.Compile("[0-9]+")
	if err != nil {
		fmt.Println(err)
	}

	if r.MatchString(str) {
		fmt.Println("String contains only numbers")
	} else {
		fmt.Println("String does not contain only numbers")
	}
}

This code is written in Go and checks if a string contains only numbers. It begins by creating a variable called str with the value being a string of numbers. Next, a regular expression is created using the Regexp library to define a set of patterns. It then checks if the str variable matches the expression pattern, and if so, prints a message saying the string contains only numbers. If not, it prints a message saying the string does not contain only numbers.

go