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

求一合法数字正则表达式,有答案马上结贴
正常正数负数都没问题
非法数字就不行
例如
1.1.1
1.a
.124
a.1


------解决方案--------------------
String str="-1.001";
boolean flag=str.matches("(-?)(\\d+|([0]|[1-9]+)\\.\\d+)");
System.out.print(flag);
------解决方案--------------------
上面那个有问题
Java code
        String str="-1.001";
        boolean flag=str.matches("(-?)(\\d+|([0]|[1-9]\\d+)\\.\\d+)");
        System.out.print(flag);

------解决方案--------------------
-?([0]|([1-9]\\d+))(\\.\\d+)?
整数部分要不就一个0,要不就是以1-9开头的数字,小数点及分数部分可有可无。
------解决方案--------------------
探讨

-?([0]|([1-9]\\d+))(\\.\\d+)?
整数部分要不就一个0,要不就是以1-9开头的数字,小数点及分数部分可有可无。

------解决方案--------------------
我也写一个。
Java code

String str="-101.1";
System.out.print(str.matches("[-+]?([1-9]\\p{Digit}*|[0])(.\\p{Digit}*[1-9])?"));

------解决方案--------------------
探讨

-?([0]|([1-9]\\d+))(\\.\\d+)?
整数部分要不就一个0,要不就是以1-9开头的数字,小数点及分数部分可有可无。

------解决方案--------------------
Java code
        
String str="-1";
boolean flag=str.matches("(-?)([0]|[1-9]\\d*)(\\.\\d+)?");
System.out.print(flag);

------解决方案--------------------
Java code
public class Test {
    static void test(String input){
        System.out.println(input.matches("(-?)([0]|([1-9]\\d+))([.]\\d+)?"));
    }
    public static void main(String[] args) {
        test("123");
        test("-123");
        test("11.22");
        test("-11.22");
        test("0.123");
        test("-0.123");
        test("-11.");
        test("11.22.33");
        test("-01.2");
        test(".123");
        test("a.2");
    }
}