上次C#考试的时候,遇到了判断输入的是否为数字。于是,今天写出了java版本的判断方法。
使用正则表达式
说实话,正则表达式绝非一般人能懂。于是,我只好偷懒了,去网上找了一个比较精准的,至于正则的意思,我也懒得解释了。
不说了,上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | /* * 需要导入包: * import java.util.regex.Matcher; * import java.util.regex.Pattern; */ public boolean findNuminRegex(String s){ /* * 使用正则表达式去匹配正浮点数. */ Pattern p = Pattern.compile("^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$");//设置正则表达式 Matcher m = p.matcher(s);//匹配 return m.find(); } |
使用try-catch
不瞒大家,这个是最简单的,我在考试的时候就是用的这个。
思路是:把一个String转换成Double(在不用区分整数与浮点数的情况下),如果报错就可以用catch捕获.
不说,上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public boolean findNuminTryCatch(String s){ /* * 使用try-catch判断是否为数字. */ boolean find = true; try { double dNum = Double.parseDouble(s); } catch (Exception e) { // TODO: handle exception find=false; } return find; } |
很简单吧..哈哈……
测试类,及所有代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 测试. * * @author Ruidong_pu * @version 2012.12.21 */ public class TestTop { public boolean findNuminRegex(String s){ /* * 使用正则表达式去匹配正浮点数. */ Pattern p = Pattern.compile("^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$");//设置正则表达式 Matcher m = p.matcher(s);//匹配 return m.find(); } public boolean findNuminTryCatch(String s){ /* * 使用try-catch判断是否为数字. */ boolean find = true; try { double dNum = Double.parseDouble(s); } catch (Exception e) { // TODO: handle exception find=false; } return find; } public static void main(String []args) { // TODO Auto-generated method stu TestTop t =new TestTop(); Scanner scanner = new Scanner(System.in); System.out.println("请输入一个数字:"); Object o=scanner.next(); /*使用正则表达式部分. System.out.println(t.findNuminRegex(o.toString())); */ /* * 使用try-catch部分. */ System.out.println(t.findNuminTryCatch(o.toString())); } } |
常用的部分正则表达式
17种常用正则表达式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | "^\\d+$" //非负整数(正整数 + 0) "^[0-9]*[1-9][0-9]*$" //正整数 "^((-\\d+)|(0+))$" //非正整数(负整数 + 0) "^-[0-9]*[1-9][0-9]*$" //负整数 "^-?\\d+$" //整数 "^\\d+(\\.\\d+)?$" //非负浮点数(正浮点数 + 0) "^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$" //正浮点数 "^((-\\d+(\\.\\d+)?)|(0+(\\.0+)?))$" //非正浮点数(负浮点数 + 0) "^(-(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*)))$" //负浮点数 "^(-?\\d+)(\\.\\d+)?$" //浮点数 "^[A-Za-z]+$" //由26个英文字母组成的字符串 "^[A-Z]+$" //由26个英文字母的大写组成的字符串 "^[a-z]+$" //由26个英文字母的小写组成的字符串 "^[A-Za-z0-9]+$" //由数字和26个英文字母组成的字符串 "^\\w+$" //由数字、26个英文字母或者下划线组成的字符串 "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$" //email地址 "^[a-zA-z]+://(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?$" //url |