zoukankan      html  css  js  c++  java
  • java中判断一个字符串是否“都为数字”和“是否包含数字”和“截取数字”(转)

      1. 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; 
  • 相关阅读:
    mybatis xml中是sql语句报错: Error creating document instance. Cause: org.xml.sax.SAXParseException: The
    先排序,后取前xx条数据
    SQL判断字段是否为空,为NULL,且连续两个字段降序排列(oracle)
    double数据保留两位
    ajax在echart代码中的正确使用
    List集合去重排序
    如何把项目中的lib下的jar包,本机上的jar包导入项目中引用
    MongoVue如何执行JS文件
    三维叠加标签代码
    beatfullsoup
  • 原文地址:https://www.cnblogs.com/huideng/p/3980644.html
Copyright © 2011-2022 走看看