Java正则表达式,可用来进行判断一个字符串是否为所需。在进行端口号检查时,经常要对输入的内容进行判断,方法如下。
一、判断字符串是否为正整数。
if (!str.matches("^[0-9]*[1-9][0-9]*$")) {
return -1;
}
或
Pattern pattern = Pattern.compile("^[0-9]*[1-9][0-9]*$");
if (!pattern.matcher(str).matches()) {
return -1;
}
二、判断字符串是否为非负整数。
if (!str.matches("^[0-9]*[0-9]*$")) {
return -1;
}
或
Pattern pattern = Pattern.compile("^[0-9]*[0-9]*$");
if (!pattern.matcher(str).matches()) {
return -1;
}
三、判断字符串是否为非空且为非负整数。
if (!str.matches("^[0-9]+[0-9]*$")) {
return -1;
}
或
Pattern pattern = Pattern.compile("^[0-9]+[0-9]*$");
if (!pattern.matcher(str).matches()) {
return -1;
}
或
if (str.isEmpty()) {
return -1;
}
if (!str.matches("^[0-9]*[0-9]*$")) {
return -1;
}
或
if (str == null) {
return -1;
}
Pattern pattern = Pattern.compile("^[0-9]*[0-9]*$");
if (!pattern.matcher(str).matches()) {
return -1;
}
附:非正则表达式方法
String str = "";
for(int i = 0; i < strDec.length(); i++) {
char c = strDec.charAt(i);
if ((c>=0x30) && (c<=0x39)) {
str += c;
} else {
//strDec.replace(c, null);
}
}
if (str == null) {
return -1;
}