@Test public void regex() {//匹配教务系统课程 // String content = "公共机座 (1-10)".replaceAll(" ",""); String content = "6A-411公共机房50座 (1-10)".replaceAll(" ","");//标准格式 //6A-411;1-10;50 // String pattern = "^(\d+)([a-zA-Z])-(\d+)([u2E80-u9FFF]+)(\d+)([\u2E80-\u9FFF]+)......";//原始完全匹配 String pattern = "^(?<arg1>\d+\S+(-)(\d+))([u2E80-u9FFF]+)(?<arg2>\d+)([\u2E80-\u9FFF]+).(?<arg3>\S+)."; String [] items = content.split(pattern); StringBuilder temp = new StringBuilder(); for(String item : items) { temp.append(item); } System.out.println(temp); Matcher matcher = Pattern.compile(pattern).matcher(content); if(matcher.matches()){ System.out.println("arg1:" + matcher.group("arg1")); System.out.println("arg2:" + matcher.group("arg2")); System.out.println("arg3:" + matcher.group("arg3")); } System.out.println(content); }
输出:
arg1:6A-411 arg2:50 arg3:1-10 6A-411公共机房50座(1-10)
正则的用途:匹配、搜索、替换、验证
1.要点1:[]用于仅能匹配一个字符
2.要点2:()用于固定某种字符串格式
3.要点3:中文utf8范围:[u2E80-u9FFF]
4.要点4:在正则表达式中设置参数断点格式:(?<argmentName>(regex1)(regex2)(regexN))