publicclassTest1{publicstaticvoidmain(String[] args){List<String> strs0 =newArrayList<>();List<String> strs1 =newArrayList<>();// Pattern p = Pattern.compile("[^0-9\\-.]+");Pattern p =Pattern.compile("\\d+(\\.\\d+)?");Matcher m = p.matcher("0.8-11增至2.4-3.0");while(m.find()){// 匹配下一个,是否匹配成功
strs0.add(m.group(0));// 获取匹配到的子串
strs1.add(m.group(1));// 获取匹配到的子串的 正则括号 里的内容}System.out.println(strs0);System.out.println(strs1);}}
输出结果
[0.8, 11, 2.4, 3.0]
[.8, null, .4, .0]
代码示例2
String str ="{1234}AA{56}AA{78}AA";try{Matcher matcher =Pattern.compile("\\{(\\d?(\\d?))(\\d?).?}").matcher(str);while(matcher.find()){int num = matcher.groupCount();for(int i =0; i <= num; i++){String group = matcher.group(i);System.out.println(group);}System.out.println();}}catch(Exception e){
e.printStackTrace();}}