如何确定字符串是否包含非字母数字字符?
我需要一种方法来告诉我字符串是否包含非字母数字字符。
例如,如果字符串是“abcdef?”或“abcdefà”,该方法必须返回 true。
I need a method that can tell me if a String has non alphanumeric characters.
For example if the String is "abcdef?" or "abcdefà", the method must return true.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
使用 Apache Commons Lang:
或者迭代 String 的字符并检查:
您还剩下一个问题:
您的示例字符串“abcdefà”是字母数字,因为
à
是一个字母。但我认为您希望它被视为非字母数字,对吗?!所以你可能想使用正则表达式:
Using Apache Commons Lang:
Alternativly iterate over String's characters and check with:
You've still one problem left:
Your example string "abcdefà" is alphanumeric, since
à
is a letter. But I think you want it to be considered non-alphanumeric, right?!So you may want to use regular expression instead:
一种方法是使用 String 类本身来做到这一点。
假设您的字符串是这样的:
另一个是使用外部库,例如 Apache commons:
One approach is to do that using the String class itself.
Let's say that your string is something like that:
one other is to use an external library, such as Apache commons:
您必须遍历字符串中的每个字符并检查
Character.isDigit(char);
或Character.isletter(char);
或者,您可以使用正则表达式。
You have to go through each character in the String and check
Character.isDigit(char);
orCharacter.isletter(char);
Alternatively, you can use regex.
使用此函数检查字符串是否为字母数字:
它节省了导入外部库的麻烦,并且如果您以后希望对字符串执行不同的验证检查,可以轻松修改代码。
Use this function to check if a string is alphanumeric:
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.
如果您可以使用 Apache Commons 库,那么 Commons-Lang
StringUtils
有一个名为isAlphanumeric()
的方法,可以满足您的需求。If you can use the Apache Commons library, then Commons-Lang
StringUtils
has a method calledisAlphanumeric()
that does what you're looking for.string.matches("^\\W*$");
应该做你想要的,但它不包含空格。string.matches("^(?:\\W|\\s)*$");
也匹配空格。string.matches("^\\W*$");
should do what you want, but it does not include whitespace.string.matches("^(?:\\W|\\s)*$");
does match whitespace as well.您可以使用 Java.lang 中的 Character 类的 isLetter(char c) 静态方法。
You can use isLetter(char c) static method of Character class in Java.lang .
虽然它不适用于数字,但您可以检查小写和大写值是否相同,对于非字母字符它们将相同,您应该在此之前检查数字以获得更好的可用性
Though it won't work for numbers, you can check if the lowercase and uppercase values are same or not, For non-alphabetic characters they will be same, You should check for number before this for better usability
我必须检查一个字符串至少包含 1 个字母和 1 个数字 - 我的解决方案如下
I had to check a string contains at least 1 letter and 1 digit - my solution below