包括小数,负号,都认为是true,但是小数点和负号的位置都必须正确1.1     true
-1.2    true
1.2-    false
1.1.1   false
12      true
1.-2    false

解决方案 »

  1.   

    public static boolean isNumber(String str) {
            str=str.trim();
            String pattern = "^[0-9]+$";
            return str.matches(pattern);
        }
      

  2.   

    抱歉上面的有错,
    可以用apache commons-lang里面的NumberUtils
      

  3.   

    String pattern = "^\\-?\d+\\.\\d+";
      

  4.   

    String pattern = "^\\-?\d+\\.\\d+";======这个失败!
      

  5.   

    我有个同事说,直接拿改字符窜去
    new BigDecimal();如果出异常,就证明他不是数字。
    这个方法实在是猥琐啊。
      

  6.   

    String reg="^(\\+|-)?\\d+.?\\d+$";注:\\+表示正数,即+0.5也认为正确,如果没有这种需求,换成String reg="^-?\\d+.?\\d+$";
      

  7.   


    借用LS的思路改一下(你的那个对于"0."也会匹配,用++就好了)
    String reg1="^(\\+|-)?\\d+(.\\d++)?$";
    or
    String reg1="^-?\\d+(.\\d++)?$";
      

  8.   

    不好意思,更正一下上面的刚想起来小数点 . 也是正则表达式的关键字,需要用转义符屏蔽,改成
    如下String reg1="^(\\+|-)?\\d+(\\.\\d++)?$";
    or
    String reg1="^-?\\d+(\\.\\d++)?$";
      

  9.   

    ^(?:\+|-)?\d+(?:\.\d+)?$ 试试这个
    http://community.csdn.net/Expert/topic/5496/5496539.xml?temp=2.822512E-02
      

  10.   

    import java.util.regex.*;
    public class a{public static void main(String[] args){String s="^-?\\d+\\.?\\d+$";
    Pattern p=Pattern.compile(s);
    Matcher m;
    String w;w="1.1";
    m=p.matcher(w);
    System.out.println("1.1="+m.matches());w="-1.2";
    m=p.matcher(w);
    System.out.println("-1.2="+m.matches());w="1.2-";
    m=p.matcher(w);
    System.out.println("1.2="+m.matches());w="1.1.1";
    m=p.matcher(w);
    System.out.println("1.1.1="+m.matches());w="12";
    m=p.matcher(w);
    System.out.println("12="+m.matches());w="1.-2";
    m=p.matcher(w);
    System.out.println("1.-2="+m.matches());System.gc();
    }
    }