To check if a string contains only alphabets and numbers in Go, you can use regular expressions from the regexp
package.
In this example,
regexp
package to use regular expressions.MatchString
method of the regular expression to check if the string matches the pattern.containsOnlyAlphabetsAndNumbers
will be true
, otherwise false
.package main
import (
"fmt"
"regexp"
)
func main() {
str := "Hello123"
pattern := regexp.MustCompile("^[a-zA-Z0-9]+$")
containsOnlyAlphabetsAndNumbers := pattern.MatchString(str)
fmt.Println("String contains only alphabets and numbers:", containsOnlyAlphabetsAndNumbers)
}
String contains only alphabets and numbers: true
In this tutorial, we learned How to Check if String contains only Alphabets and Numbers in Go language with well detailed examples.