今天在写一个用于模拟数据的工具,不提供前端界面,在命令行上输入指令执行即可。对输入的命令需要先验证,当然选择正则表达式最为合适, 然后将指令的参数提取出来,再进行下一步的封装。举例如下:
//可以输入的参数值 private static String charsregx = "[A-Za-z0-9]|[^\\x00-\\xff]" ; public static void main(String[] args){ Scanner input = new Scanner(System.in); String line = null ; while(true){ line = input.nextLine() ; //获取输入的数据 if(StringUtils.contains(line, "exit") || StringUtils.contains(line,"over")){ System.exit(1); //关闭 break ; } if(StringUtils.isBlank(line)){ continue ; } /* * 例如有以下的这些命令可供操作 * 1,按照网元类型执行: send -t XX -f XX * 2,按照网元ID执行: send -i XX -f XX * 3,查看当前的任务列表:task -l * 4,查看指定任务的当前情况: task -n XX * 5,取消指定的任务:cancel -n XX * 6,关闭:exit/over * 7,帮助:help * 注: t:type * f:file * i:id * l:list * n:name * */ ///////////////以send命名为例////////////// //用于send命令的正则匹配 if(validateSendCmd(line)){ //验证全行是否匹配 //参数的正则字符串 String argsRegx = "-[tif]{1}\\s+([A-Za-z0-9]|[^\\x00-\\xff])+" ; Pattern pattern = Pattern.compile(argsRegx) ; Matcher m = pattern.matcher(line) ; while(m.find()){ //获取每个参数 System.out.println(m.group()); //TODO 封装每个参数信息,后面传递给执行业务逻辑处理 } }else{ System.out.println("命令行格式错误"); } } } |
/** * send命令的以下四种支持的格式 * 1, send -t type * 2, send -t type -f file * 3, send -i id * 4, send -i id -f file * */ private static boolean validateSendCmd(String cmd){ Set<String> needArgs = new HashSet<String>() ; Set<String> attchArgs = new HashSet<String>() ; //用于send命令的正则匹配 if(StringUtils.startsWith(cmd.trim(), "send")){ needArgs.add("t") ; needArgs.add("i") ; attchArgs.add("f") ; //获取正则匹配表达式 Set<String> regxSet = getCmdRegx("send", needArgs, attchArgs) ; if(regxSet == null || regxSet.size() == 0){ return false ; } for(String rgx : regxSet){ //System.out.println(rgx); Pattern pattern = Pattern.compile(rgx) ; Matcher m = pattern.matcher(cmd) ; if(m.matches()){ return true ; } } } return false ; } |
/** Set<String> attchArgs){ |
这里应用到了正则表达式,摘录几个挺有用的表达式:
匹配中文字符的正则表达式 | [\u4e00-\u9fa5] |
匹配双字节字符(包括汉字在内)。 应用:计算字符串的长度(一个双字节字符长度计2,ASCII字符计1) | [^\x00-\xff] |
匹配空行的正则表达式 | \n[\s| ]*\r |
匹配首尾空格的正则表达式 | (^\s*)|(\s*$) |
验证Email地址 | "^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$" |
转载于:https://blog.51cto.com/dengshuangfu/1621112