@Test public void test1() { /** * .{3}(?=a)代表着这样的功能: * 查找给出的字符串中符合a前面有三个字母的这样的子串,当然取得的子串不包括(?=a) */ Pattern p = Pattern.compile(".{3}(?=a)"); String s1 = "444a66b"; Matcher m = p.matcher(s1); while (m.find()) { System.out.println(m.group()); } } @Test public void test2() { /** * 通过上面的(?=X)下面来测试和设想一下(?!a),api解释为 * (?!X) X,通过零宽度的负lookahead,所以对比一下很容易想到 * \\d{3}(?!a)代表着连续三个数字的后面出现的字符不是a的匹配, * 所以字符串444a666b只有一个匹配子串666 * 字符串444b666b两个匹配444 666 * 字符串444a666a都不匹配 */ Pattern p = Pattern.compile("\\d{3}(?!a)");//(?!X) X,通过零宽度的负lookahead String s3 = "444b666b"; Matcher m = p.matcher(s3); while (m.find()) { System.out.println(m.group()); } } @Test public void test3() { /** * lookbehind * (?<=[a-z]+)(\d) 前边是a-z */ String patternStr1 = "(?<=[a-z]+)(\\d)"; Pattern p = Pattern.compile(patternStr1); Matcher m = p.matcher("sdfafds8435423"); while (m.find()) System.out.println(m.group()); // 运行结果:8 } @Test public void test4() { /** * lookbehind * (?<=[a-z]+)(\d) 前边不是a-z */ String patternStr1 = "(?<![a-z])(\\d+)"; Pattern p = Pattern.compile(patternStr1); Matcher m = p.matcher("sdfafds8435423"); while (m.find()) System.out.println(m.group()); // 运行结果:435423 } @Test public void test5() { /** * (?:X)的作用是取消分组,看结果没有2这个组 */ String patternStr1 = "([a-z]+)(?:\\d)"; Pattern p = Pattern.compile(patternStr1); Matcher m = p.matcher("sdfafds8435423"); while (m.find()) { System.out.println(m.group(0)); System.out.println(m.group(1)); System.out.println(m.group(2)); //sdfafds8 //sdfafds //java.lang.IndexOutOfBoundsException: No group 2 } }
java 正则特殊构造Special constructs (named-capturing and non-capturing)
最新推荐文章于 2021-02-13 12:45:05 发布