日期:2014-05-20  浏览次数:20818 次

求表示数字的正则表达式。
包括小数,负号,都认为是true,但是小数点和负号的位置都必须正确

1.1           true
-1.2         true
1.2-         false
1.1.1       false
12             true
1.-2         false



------解决方案--------------------
String reg= "^(\\+|-)?\\d+.?\\d+$ ";

注:\\+表示正数,即+0.5也认为正确,如果没有这种需求,换成

String reg= "^-?\\d+.?\\d+$ ";
------解决方案--------------------

借用LS的思路改一下(你的那个对于 "0. "也会匹配,用++就好了)


String reg1= "^(\\+|-)?\\d+(.\\d++)?$ ";
or
String reg1= "^-?\\d+(.\\d++)?$ ";
------解决方案--------------------
不好意思,更正一下上面的

刚想起来小数点 . 也是正则表达式的关键字,需要用转义符屏蔽,改成
如下

String reg1= "^(\\+|-)?\\d+(\\.\\d++)?$ ";
or
String reg1= "^-?\\d+(\\.\\d++)?$ ";

------解决方案--------------------
^(?:\+|-)?\d+(?:\.\d+)?$ 试试这个
http://community.csdn.net/Expert/topic/5496/5496539.xml?temp=2.822512E-02
------解决方案--------------------
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();
}
}