go

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


I am trying to check the username whether is only containing alphabetic characters. What is the idiomatic way to check it in Go?


Solution

  • 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 since go1.21:

    package main
    
    import (
        "fmt"
        "strings"
        "unicode"
    )
    
    func IsLetter(s string) bool {
        return !strings.ContainsFunc(s, func(r rune) bool {
            return !unicode.IsLetter(r)
        })
    }
    
    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"
    
    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 since go1.21:

    package main
    
    import (
        "fmt"
        "strings"
        "unicode"
    )
    
    func IsLetter(s string) bool {
        return !strings.ContainsFunc(s, func(r rune) bool {
            return (r < 'a' || r > 'z') && (r < 'A' || r > 'Z')
        })
    }
    
    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
    }