Search code examples
stringgounicode-string

Determine whether a character is a letter or number


Given that Go strings are unicode, is there a way to safely determine whether a character (such as the first letter in a string) is a letter or a number? In the past I would just check against ASCII character ranges, but I doubt that would be very reliable with unicode strings.


Solution

  • You can always use func IsNumber(r rune) bool in the unicode package:

    if unicode.IsNumber(rune) { ... }
    

    Just be aware that this includes more characters than just 0-9, such as roman numbers (eg. Ⅲ) or fractions (eg. ⅒) . If you specifically only want to check 0-9, you should instead do like you've done in the past (yes, it is UTF-8 safe):

    if rune >= 48 && rune <= 57 { ... }
    

    or

    if rune >= '0' && rune <= '9' { ... } // as suggested by Martin Gallagher
    

    For letters, the unicode package has a similar function: func IsLetter(r rune) bool