[英]Check if String doesn't have any letters but only numbers
How can I check if a String in java has no letters, only numbers? java - 如何检查java中的字符串是否没有字母,只有数字? Thank you for the answer
谢谢你的回答
You can use regex: yourString.matches("\\\\d+")
您可以使用正则表达式:
yourString.matches("\\\\d+")
\\\\d
means one digit 0-9, +
means one or more, combined \\\\d+
is equal to one or more digit :) \\\\d
表示一位数字 0-9, +
表示一位或多位,组合\\\\d+
等于一位或多位数字 :)
Use a regular expression:使用正则表达式:
string.matches("\\d*");
"\\d*"
means "A digit (0-9) zero or more times." "\\d*"
表示“一个数字 (0-9) 零次或多次”。 Alternatively, you can replace "*" with "+" to mean "one or more times".或者,您可以将“*”替换为“+”以表示“一次或多次”。
org.apache.commons.lang.StringUtils.isNumeric(String) verifies that all characters in the input string are digits. org.apache.commons.lang.StringUtils.isNumeric(String) 验证输入字符串中的所有字符都是数字。
It's implemented as (if you don't want the 3rd-party dependency):它实现为(如果您不想要第 3 方依赖项):
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (Character.isDigit(str.charAt(i)) == false) {
return false;
}
}
return true;
You can just iterate over the string and check each character (possibly more efficient than doing it with a regex, if performance is a consideration).您可以遍历字符串并检查每个字符(如果考虑性能,可能比使用正则表达式更有效)。
boolean isAllDigit(String s) {
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) < '0' || s.charAt(i) > '9') {
return false;
}
}
return true;
}
Why don't you just put it in a try/catch?你为什么不把它放在 try/catch 中?
String number="a123.2";
try {
Double.parseDouble(number);
System.out.println("It's a number");
} catch (Exception e) {
System.out.println("This is not a number!");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.