Skip to content

Instantly share code, notes, and snippets.

@gexiangdong
Last active March 3, 2019 01:03
Show Gist options
  • Save gexiangdong/24c8fec0da74fc803fe099b73426eb5f to your computer and use it in GitHub Desktop.
Save gexiangdong/24c8fec0da74fc803fe099b73426eb5f to your computer and use it in GitHub Desktop.
Character.isLetterOrDigit 无法判断一个字符(可能是中文)是否是字母或数字

判断一个字符是否是字母或数字,最原始的办法可以去比较是否在 0-9, a-z, A-Z 之间。这样写代码稍稍有点长。

char c;
...
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <== 'Z') || (c >= '0' && c <= '9')){
}

发现 Character 类有一个 isLetterOrDigit(char ch)方法,看名字似乎是解决这个问题,但试用一下发现 / \ . 等标点可以返回false,但遇到中文会返回true。 无法实现相应功能。

apache commons-lang 中的 CharUtils.isAsciiAlphanumeric(char c) 可以实现这个功能,并且遇到中文字符也会返回false。但需要增加一个依赖。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment