OneBite.Dev - Coding blog in a bite size

check if a string contains only alphanumeric characters in Go

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

package main

import (
	"fmt"
	"regexp"
)

func main() {
	// a string to check if it contains only alphanumeric characters
	alphanum := "abc123"

	// regexp to check if a string only contains alphanumeric characters
	reg := regexp.MustCompile(`[a-zA-Z0-9]+`)

	// check if the string provided only contains alphanumeric characters
	result := reg.MatchString(alphanum)

	// print the result
	fmt.Println(result)
}

This code uses the regexp package to check if a string contains only alphanumeric characters. First, a string “abc123” is provided to check. Then the regexp package is imported which provides a function to match strings against the given regular expression, which in this example is [a-zA-Z0-9]+ (a letter or digit). Finally, the MatchString function is used to check if “abc123” contains only alphanumeric characters. The result is printed, which will be True if the string only contains alphanumeric characters.

go