Java, , , , , :
boolean isInteger = Pattern.matches("^\d*$", myString);
, Integer.parseInt(myString) , . -. , int 10 . , ^-?0*\d{1,10}$. , .
. . , , parseInt . :
static boolean wouldParseIntThrowException(String s) {
if (s == null || s.length() == 0) {
return true;
}
char[] max = Integer.toString(Integer.MAX_VALUE).toCharArray();
int i = 0, j = 0, len = s.length();
boolean maybeOutOfBounds = true;
if (s.charAt(0) == '-') {
if (len == 1) {
return true;
}
i = 1;
max[max.length - 1]++;
}
while (i < len && s.charAt(i) == '0') {
i++;
}
if (max.length < len - i) {
return true;
} else if (len - i < max.length) {
maybeOutOfBounds = false;
}
while (i < len) {
char digit = s.charAt(i++);
if (digit < '0' || '9' < digit) {
return true;
} else if (maybeOutOfBounds) {
char maxdigit = max[j++];
if (maxdigit < digit) {
return true;
} else if (digit < maxdigit) {
maybeOutOfBounds = false;
}
}
}
return false;
}
, . , .
#, , , TryParse. true, . , parseInt, null .
, , . :
private static Pattern QUITE_ACCURATE_INT_PATTERN = Pattern.compile("^-?0*\\d{1,10}$");
static Integer tryParseIntegerWhichProbablyResultsInOverflow(String s) {
Integer result = null;
if (!wouldParseIntThrowException(s)) {
try {
result = Integer.parseInt(s);
} catch (NumberFormatException ignored) {
}
}
return result;
}
static Integer tryParseIntegerWhichIsMostLikelyNotEvenNumeric(String s) {
Integer result = null;
if (s != null && s.length() > 0 && QUITE_ACCURATE_INT_PATTERN.matcher(s).find()) {
try {
result = Integer.parseInt(s);
} catch (NumberFormatException ignored) {
}
}
return result;
}
static Integer tryParseInteger(String s) {
Integer result = null;
if (s != null && s.length() > 0) {
try {
result = Integer.parseInt(s);
} catch (NumberFormatException ignored) {
}
}
return result;
}
static Integer tryParseIntegerWithoutAnyChecks(String s) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException ignored) {
}
return null;
}