java中判断一个字符串是否“都为数字”和“是否包含数字”和“截取数字”

java中判断一个字符串是否“都为数字”和“是否包含数字”和“截取数字”

原文地址:http://ahomeeye.iteye.com/blog/842922

http://cherryqq.iteye.com/blog/406355

在javascript中有一个方法isDigit()使用来判断一个字符串是否都是数字,在java的字符串处理方法中没有这样的方法,觉得常常需要用到,于是上网搜了一下,整理出了两个用正则表达式匹配的判断方法,如下; 

Java代码  收藏代码
  1. // 判断一个字符串是否都为数字  
  2. public boolean isDigit(String strNum) {  
  3.     return strNum.matches("[0-9]{1,}");  
  4. }  
  5.   
  6. // 判断一个字符串是否都为数字  
  7. public boolean isDigit(String strNum) {  
  8.     Pattern pattern = Pattern.compile("[0-9]{1,}");  
  9.     Matcher matcher = pattern.matcher((CharSequence) strNum);  
  10.     return matcher.matches();  
  11. }
  12. //截取数字  
  13. public String getNumbers(String content) {  
  14.     Pattern pattern = Pattern.compile("\d+");  
  15.     Matcher matcher = pattern.matcher(content);  
  16.     while (matcher.find()) {  
  17.        return matcher.group(0);  
  18.     }  
  19.     return "";  
  20. }  
  21.   
  22. // 截取非数字  
  23. public String splitNotNumber(String content) {  
  24.     Pattern pattern = Pattern.compile("\D+");  
  25.     Matcher matcher = pattern.matcher(content);  
  26.     while (matcher.find()) {  
  27.         return matcher.group(0);  
  28.     }  
  29.     return "";  
  30. }  
  31. // 判断一个字符串是否含有数字
    public boolean hasDigit(String content) {
    boolean flag = false;
    Pattern p = Pattern.compile(".*\d+.*");
    Matcher m = p.matcher(content);
    if (m.matches())
    flag = true;
    return flag;
    }
java中判断字符串是否为数字的三种方法 
1用JAVA自带的函数 
public static boolean isNumeric(String str){ 
  for (int i = str.length();--i>=0;){   
   if (!Character.isDigit(str.charAt(i))){ 
    return false; 
   } 
  } 
  return true; 


2用正则表达式 
public static boolean isNumeric(String str){ 
    Pattern pattern = Pattern.compile("[0-9]*"); 
    return pattern.matcher(str).matches();    


3用ascii码 

public static boolean isNumeric(String str){ 
   for(int i=str.length();--i>=0;){ 
      int chr=str.charAt(i); 
      if(chr<48 || chr>57) 
         return false; 
   } 
   return true; 
原文地址:https://www.cnblogs.com/luolizhi/p/4946091.html