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

I am trying to check the username if it contains only alphabetic characters. What an idiomatic way to test this in Go?

+19
source share
4 answers

you can use unicode.IsLetteras this working example 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 a limited range, for example. 'a' .. 'z' and 'A' .. 'Z', you can use this working code example:

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 a limited range, for example. 'a' .. 'z' and 'A' .. 'Z', you can use this working code example:

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
}
+31
source

Here's how I do it:

import "strings"

const alpha = "abcdefghijklmnopqrstuvwxyz"

func alphaOnly(s string) bool {
   for _, char := range s {  
      if !strings.Contains(alpha, strings.ToLower(string(char))) {
         return false
      }
   }
   return true
}
+4
source

, ascii, , , - [[:alpha:]] [A-Za-z]

isAlpha := regexp.MustCompile(`^[A-Za-z]+$`).MatchString

for _, username := range []string{"userone", "user2", "user-three"} {
    if !isAlpha(username) {
        fmt.Printf("%q is not valid\n", username)
    }
}

https://play.golang.org/p/lT9Fki7tt7

+3

, -

func isLetter(c rune) bool {
    return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')
}

func isWord(s string) bool {
    for _, c := range s {
        if (!isLetter(c)) {
            return false
        }
    }
    return true
}
0

Source: https://habr.com/ru/post/1648946/


All Articles