How to check if a string only contains alphabetic characters in Go?

you may use unicode.IsLetter like this working sample code:

package main

import "fmt"
import "unicode"

func IsLetter(s string) bool {
    for _, r := range s {
        if !unicode.IsLetter(r) {
            return false
        }
    }
    return true
}
func main() {
    fmt.Println(IsLetter("Alex")) // true
    fmt.Println(IsLetter("123"))  // false
}

or if you have limited range e.g. ‘a’..’z’ and ‘A’..’Z’, you may use this working sample code:

package main

import "fmt"

func IsLetter(s string) bool {
    for _, r := range s {
        if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') {
            return false
        }
    }
    return true
}
func main() {
    fmt.Println(IsLetter("Alex"))  // true
    fmt.Println(IsLetter("123 a")) // false

}

or if you have limited range e.g. ‘a’..’z’ and ‘A’..’Z’, you may use this working sample code:

package main

import "fmt"
import "regexp"

var IsLetter = regexp.MustCompile(`^[a-zA-Z]+$`).MatchString

func main() {
    fmt.Println(IsLetter("Alex")) // true
    fmt.Println(IsLetter("u123")) // false
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)