[英]How to determine if a String has non-alphanumeric characters?
I need a method that can tell me if a String has non alphanumeric characters.我需要一种方法来告诉我字符串是否包含非字母数字字符。
For example if the String is "abcdef?"例如,如果字符串是“abcdef?” or "abcdefà", the method must return true.
或“abcdefà”,该方法必须返回true。
Using Apache Commons Lang:使用 Apache Commons Lang:
!StringUtils.isAlphanumeric(String)
Alternativly iterate over String's characters and check with:或者迭代字符串的字符并检查:
!Character.isLetterOrDigit(char)
You've still one problem left: Your example string "abcdefà" is alphanumeric, since à
is a letter.您还剩下一个问题:您的示例字符串 "abcdefà" 是字母数字,因为
à
是一个字母。 But I think you want it to be considered non-alphanumeric, right?!但我认为您希望它被视为非字母数字,对吗?!
So you may want to use regular expression instead:所以你可能想改用正则表达式:
String s = "abcdefà";
Pattern p = Pattern.compile("[^a-zA-Z0-9]");
boolean hasSpecialChar = p.matcher(s).find();
One approach is to do that using the String class itself.一种方法是使用 String 类本身来做到这一点。 Let's say that your string is something like that:
假设您的字符串是这样的:
String s = "some text";
boolean hasNonAlpha = s.matches("^.*[^a-zA-Z0-9 ].*$");
one other is to use an external library, such as Apache commons:另一种是使用外部库,例如 Apache commons:
String s = "some text";
boolean hasNonAlpha = !StringUtils.isAlphanumeric(s);
You have to go through each character in the String and check Character.isDigit(char);
您必须遍历字符串中的每个字符并检查
Character.isDigit(char);
or Character.isletter(char);
或
Character.isletter(char);
Alternatively, you can use regex.或者,您可以使用正则表达式。
Use this function to check if a string is alphanumeric:使用此函数检查字符串是否为字母数字:
public boolean isAlphanumeric(String str)
{
char[] charArray = str.toCharArray();
for(char c:charArray)
{
if (!Character.isLetterOrDigit(c))
return false;
}
return true;
}
It saves having to import external libraries and the code can easily be modified should you later wish to perform different validation checks on strings.它无需导入外部库,并且如果您以后希望对字符串执行不同的验证检查,则可以轻松修改代码。
string.matches("^\\\\W*$");
should do what you want, but it does not include whitespace.应该做你想做的,但它不包括空格。
string.matches("^(?:\\\\W|\\\\s)*$");
does match whitespace as well.也匹配空格。
如果您可以使用 Apache Commons 库,那么 Commons-Lang StringUtils
有一个名为isAlphanumeric()
的方法isAlphanumeric()
您的需求。
You can use isLetter(char c) static method of Character class in Java.lang .您可以在 Java.lang 中使用 Character 类的 isLetter(char c) 静态方法。
public boolean isAlpha(String s) {
char[] charArr = s.toCharArray();
for(char c : charArr) {
if(!Character.isLetter(c)) {
return false;
}
}
return true;
}
虽然它不适用于数字,但您可以检查小写和大写值是否相同,对于非字母字符,它们将相同,您应该在此之前检查数字以获得更好的可用性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.