lug*_*eno 69 java string alphanumeric character
我需要一个方法,可以告诉我String是否有非字母数字字符.
例如,如果字符串是"abcdef?" 或"abcdefà",该方法必须返回true.
Fab*_*ney 136
使用Apache Commons Lang:
!StringUtils.isAlphanumeric(String)
Run Code Online (Sandbox Code Playgroud)
另外迭代String的字符并检查:
!Character.isLetterOrDigit(char)
Run Code Online (Sandbox Code Playgroud)
你还有一个问题:你的示例字符串"abcdefà"是字母数字,因为它à是一个字母.但我认为你希望它被认为是非字母数字的,对吧?!
所以你可能想要使用正则表达式:
String s = "abcdefà";
Pattern p = Pattern.compile("[^a-zA-Z0-9]");
boolean hasSpecialChar = p.matcher(s).find();
Run Code Online (Sandbox Code Playgroud)
los*_*gio 26
一种方法是使用String类本身来做到这一点.让我们说你的字符串是这样的:
String s = "some text";
boolean hasNonAlpha = s.matches("^.*[^a-zA-Z0-9 ].*$");
Run Code Online (Sandbox Code Playgroud)
另一个是使用外部库,例如Apache commons:
String s = "some text";
boolean hasNonAlpha = !StringUtils.isAlphanumeric(s);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
186045 次 |
| 最近记录: |