package org.jimmy.autosearch20180821.test; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TestRegularExpression { public static void main(String[] args) { //2位数字直接匹配,3位或3位以上的数字直接匹配末尾两位数字 Pattern pattern = Pattern.compile("\d{2}(?!\d+)"); Matcher matcher = pattern.matcher("145423gdf4525243g89dgf56gxdfd123gxf4562gxd2357xgdf12gdsf36"); while(matcher.find()){ System.out.print(matcher.group() + " "); } System.out.println(); //这个在之前基础上过滤掉了前面的数字(3位或3位以上的数字不会匹配,只会匹配2位数的数字) pattern = Pattern.compile("(?<!\d+)\d{2}(?!\d+)"); matcher = pattern.matcher("145423gdf4525243g89dgf56gxdfd123gxf4562gxd2357xgdf12gdsf36"); while(matcher.find()){ System.out.print(matcher.group() + " "); } } }
直接上代码了,这次使用了?!和?<!来匹配正则表达式.
下图是运行结果.