To check if a string is alphanumeric in Go, you can use the “MustCompile() along with MatchString()” functions or the “IsLetter() along with isDigit()” functions.
Method 1: Using MustCompile() along with MatchString() functions
The regexp.MustCompile() function in Go is “used to compile a regular expression and returns a Regexp object.”
If the regular expression does not compile, the function will panic. The MatchString() method is then used to check if a string matches the regular expression.
Example
package main
import (
"fmt"
"regexp"
)
// Define a global regular expression pattern
var alphanumericRegex = regexp.MustCompile(`^[a-zA-Z0-9]+$`)
func isAlphanumeric(s string) bool {
return alphanumericRegex.MatchString(s)
}
func main() {
testStrings := []string{
"Albus123",
"Harry Potter!",
"123456",
"ABCKBKL",
}
for _, s := range testStrings {
fmt.Printf("Is '%s' alphanumeric? %v\n", s, isAlphanumeric(s))
}
}
Output
Is 'Albus123' alphanumeric? true
Is 'Harry Potter!' alphanumeric? false
Is '123456' alphanumeric? true
Is 'ABCKBKL' alphanumeric? true
Method 2: Using the IsLetter() along with IsDigit() functions
You can iterate through each string character and use the unicode package’s IsLetter() and IsDigit() functions to check if a string is alphanumeric. This method is not as efficient as the first one, but let’s see how this method works.
Example
package main
import (
"fmt"
"unicode"
)
func isAlphanumeric(s string) bool {
for _, r := range s {
if !unicode.IsLetter(r) && !unicode.IsDigit(r) {
return false
}
}
return true
}
func main() {
testStrings := []string{
"Albus123",
"Harry Potter!",
"123456",
"ABCKBKL",
}
for _, s := range testStrings {
fmt.Printf("Is '%s' alphanumeric? %v\n", s, isAlphanumeric(s))
}
}
Output
Is 'Albus123' alphanumeric? true
Is 'Harry Potter!' alphanumeric? false
Is '123456' alphanumeric? true
Is 'ABCKBKL' alphanumeric? true
That’s it.
Related posts

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.