How to Check If String is Alphanumeric in Golang

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

Go trim string

Go string.Index()

Go multiline strings

Go strings.Replace()