java 验证字符串输入没有数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7939913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validating String input has no numbers
提问by user1015523
I have found how to validate that an input is a number using try/catch but how do I go about validating that a user input is alphabetical only and contains no numbers?
我已经找到了如何使用 try/catch 验证输入是否为数字,但是如何验证用户输入是否仅按字母顺序排列且不包含数字?
回答by NPE
You could use a simple regular expression:
您可以使用一个简单的正则表达式:
if (str.matches("[a-zA-Z]+$")) {
// str consists entirely of letters
}
Note that this only works with letters A-Z
and a-z
. If you need to properly support Unicode, a better method is to loop over the characters of the string and use Character.isLetter()
.
请注意,这只适用于字母A-Z
和a-z
。如果需要正确支持 Unicode,更好的方法是遍历字符串的字符并使用Character.isLetter()
.
回答by Jeffrey
public static boolean containsNumbers(String str){
for(char ch : str.toCharArray()){
if(Character.isDigit(ch)){
return true;
}
}
return false;
}
回答by Salvatore Previti
One way is to use regular expressions.
一种方法是使用正则表达式。
private static Pattern p = Pattern.compile("^[A-Za-z]+$");
public static boolean match(String s) {
return p.matcher(s).matches();
}
One other way can be iterate through all characters in your string and check if they are alphabetical or not.
另一种方法可以遍历字符串中的所有字符并检查它们是否按字母顺序排列。