无线&移动互联网技术研发

换位思考·····
posts - 19, comments - 53, trackbacks - 0, articles - 283
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

判断字符串是否是数字串

Posted on 2009-11-23 11:33 Gavin.lee 阅读(252) 评论(0)  编辑  收藏 所属分类: java SE & EE
在我们日常开发过程中,为了安全考虑,会用到对传值进行限制,下面这段是先人用的4个方法,都是可行了,现贴如下
//    1.使用Character.isDigit(char)判断     
    public boolean isNumeric(String str) {
        
if (str == null || str.equals("")) {
            
return false;
        }

        
for (int i = str.length(); -->= 0;) {
            
if (!Character.isDigit(str.charAt(i))) {
                
return false;
            }

        }

        
return true;
    }

     

//    2.使用类型转换判断
    public boolean isNumeric2 (String str) {
        
try {   
            Integer.valueOf(str);   
            
return true;
        }
 catch (Exception e) {   
            
return false
        }
  
    }


//    3.使用正则表达式判断
    public boolean isNumeric3(String str) {
        
return str.matches("[0-9]+");    
        
//    +表示1个或多个(如"3"或"225"),*表示0个或多个([0-9]*)(如""或"1"或"22"),?表示0个或1个([0-9]?)(如""或"7")   
    }

    
//    4.使用Pattern类和Matcher
    public boolean isNumeric4(String str) {
        Pattern pattern 
= Pattern.compile("[0-9]+");   
        Matcher matcher 
= pattern.matcher((CharSequence) str);   
        
return matcher.matches();   
    }

只有注册用户登录后才能发表评论。


网站导航: