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

In this example, we defined a global variable alphanumericRegex that uses the regexp.MustCompile() function to compile an alphanumeric regular expression pattern.

The isAlphanumeric() function checks if the input string s matches the alphanumericRegex pattern using the MatchString() method.

Inside the main() function, we called the isAlphanumeric() function with several test strings and printed the results.

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

In this example, we defined an isAlphanumeric() function that accepts a string s as an argument.

Using a range loop, we iterated through each character (rune) in the string.

We then used the unicode.IsLetter() and unicode.IsDigit() checks whether the character is a letter or a digit. The function returns false if it’s neither a letter nor a digit. If all characters are letters or digits, the function returns true.

That’s it.

Leave a Comment