Java中用正则表达式判断,字符串是否全是数字
自己整理了几个正则表达式,不是很懂。。但能用。
package com.guo;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
System.out.println(isNum3("str324234"));
System.out.println(isNum3("ew2345errw"));
System.out.println(isNum3("43535334"));
System.out.println(isNum3("34"));
System.out.println(isNum3("3423_2313"));
System.out.println(isNum3("12水56"));
System.out.println(isNum3("-123456"));
System.out.println(isNum3("123456"));
}
public static boolean isDigit1(String str) {
if (str == null)
return false;
return str.matches("[0-9]{1,}");
}
public static boolean isDigit2(String strNum) {
Pattern pattern = Pattern.compile("[0-9]{1,}");
Matcher matcher = pattern.matcher(strNum);
return matcher.matches();
}
public static boolean isNum1(String strNum) {
//Pattern pattern = Pattern.compile("[0-9]*"); // 此方法只验证正数
//Pattern pattern = Pattern.compile("-[0-9]*"); // 此方法只验证负数
Pattern pattern = Pattern.compile("-?[0-9]*"); // 验证数字
// Pattern pattern = Pattern.compile("-?[0-9]+?[0-9]+");(与上一行同效果)
Matcher matcher = pattern.matcher(strNum);
return matcher.matches();
}
public static boolean isNum2(String str){
if (str == null)
return false;
return str.matches("[0-9]+");
}
public static boolean isNum3(String str) {
if (str == null)
return false;
Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");
return pattern.matcher(str).matches();
}
// 与isNum1效果相同
public static boolean isNum4(String str) {
Pattern pat = Pattern.compile("^-?[0-9]+$");
Matcher mat = pat.matcher(str);
if (mat.find()) {
return true;
} else {
return false;
}
}
}