正则表达式&自定义异常 典型案例
2016-10-24 00:00
225 查看
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { public static void main(String[] args) { System.out.println(oper(" 12.3+213.1")); } public static float oper(String s) { Float res = null; Pattern p = Pattern .compile("\\s*(\\d+)(\\.*)(\\d+)\\s*(\\+|-|\\*\\/)\\s*(\\d+)(\\.*)(\\d+)\\s*"); Matcher m = p.matcher(s); boolean b = m.matches(); if (!b) { throw new couldNotCaculateException("匹配错误"); } String s1 = m.group(1) + m.group(2) + m.group(3); String s2 = m.group(5) + m.group(6) + m.group(7); Float f1 = Float.parseFloat(s1); Float f2 = Float.parseFloat(s2); if ("+".equals(m.group(4))) { res = f1 + f2; } else if ("-".equals(m.group(4))) { res = f1 - f2; } else if ("*".equals(m.group(4))) { res = f1 * f2; } else if ("/".equals(m.group(4))) { if (f2 == 0) { throw new couldNotCaculateException("除数不能为o"); } res = f1 / f2; } return res; } } class couldNotCaculateException extends RuntimeException { private static final long serialVersionUID = -1127307315212919888L; public couldNotCaculateException(String msg) { super(msg); } }
相关文章推荐
- 正则表达式&自定义异常 典型案例
- qtp 获取弹出提示框(异常框)的文本显示信息(正则表达式和自定义函数应用)
- fck_editor 不采用正则表达式实现插入任意自定义图片标签的解决方法
- C# 利用正则表达式进行忽略大小写的字符串替换的应用--自定义高亮显示
- javascript 正则表达式小案例
- 自定义jQuery.validator 验证框架,登录验证以及自定义的正则表达式验证
- js 正则表达式验证自定义文本格式
- 实现自定义类似XML语法分析的正则表达式(原创)
- java正则表达式-案例代码
- 正则表达式提取案例1
- jquery validate.addMethod 正则表达式 (自定义验证方法)
- perl 自定义包/模块的使用(正则表达式匹配email地址和ip)
- 发布一个自己写的文件重命名工具,支持正则表达式替换和自定义规则。
- 2.15 典型正则表达式解释(1)
- php正则表达式学习(附各种案例)
- JS 正则表达式 2(案例)
- SQL调用正则表达式自定义函数(转载:CSDN)
- C# 利用正则表达式进行忽略大小写的字符串替换的应用--自定义高亮显示
- PHP正则表达式典型应用三例
- 我的正则表达式测试案例