◎위챗 : speedseoul
I Like this one.
private static final int NUMBER_MAX_LENGTH = String.valueOf(Long.MAX_VALUE).length();
public static boolean isNumber(String string) {
if (string == null || string.isEmpty()) {
return false;
}
if (string.length() >= NUMBER_MAX_LENGTH) {
try {
Long.parseLong(string);
} catch (Exception e) {
return false;
}
} else {
int i = 0;
if (string.charAt(0) == '-') {
if (string.length() > 1) {
i++;
} else {
return false;
}
}
for (; i < string.length(); i++) {
if (!Character.isDigit(string.charAt(i))) {
return false;
}
}
}
return true;
}
http://stackoverflow.com/questions/15111420/how-to-check-if-a-string-contains-only-digits-in-java
Q:
In Java for String class there is a method called matches, how to use this method to check if my string is having only digits using regular expression. I tried with below examples, but both of them returned me false as result.
String regex = "[0-9]"; String data = "23343453"; System.out.println(data.matches(regex));
String regex = "^[0-9]";
String data = "23343453";
System.out.println(data.matches(regex));
Answer:
Try
String regex = "[0-9]+";
or
String regex = "\\d+";
Where the +
means "one or more" and \d means "digit".
Note: the "double slash" gives you one slash. "\\d"
gives you: \d
You must allow for more than a digit (the +
sign) as in:
String regex = "[0-9]+";
String data = "23343453";
System.out.println(data.matches(regex));
Answer:
http://www.pretechsol.com/2013/10/how-to-check-if-string-contains-only.html#.UmgRIxAVuPA
private static boolean isNumber(final String number) {
boolean bisNumber = false;
if (number == null) {
bisNumber = false;
}
try {
Integer.parseInt(number);
bisNumber = true;
} catch (NumberFormatException ne) {
bisNumber = false;
}
return bisNumber;
}