确定字符是字母还是数字

Nai*_*rou 0 string unicode-string go

鉴于Go字符串是unicode,有没有办法安全地确定字符(例如字符串中的第一个字母)是字母还是数字?在过去,我只会检查ASCII字符范围,但我怀疑使用unicode字符串会非常可靠.

ANi*_*sus 5

您可以随时func IsNumber(r rune) boolunicode包中使用:

if unicode.IsNumber(rune) { ... }
Run Code Online (Sandbox Code Playgroud)

请注意,这包括的字符数不仅仅是0-9,例如罗马数字(例如.Ⅲ)或分数(例如⅒).如果您特别想要检查0-9,那么您应该像过去那样做(是的,它是UTF-8安全的):

if rune >= 48 && rune <= 57 { ... }
Run Code Online (Sandbox Code Playgroud)

要么

if rune >= '0' && rune <= '9' { ... } // as suggested by Martin Gallagher
Run Code Online (Sandbox Code Playgroud)

对于字母,unicode包具有类似的功能:func IsLetter(r rune)bool

  • 请注意,对于 ASCII,为了提高清晰度,您还可以使用:`if rune &gt;= '0' &amp;&amp; rune &lt;= '9' { ... }` (2认同)