import java.util.regex.*; public class RegPlus{ public static void main(String[] args){ //group(); //reference(); flags(); } //non-capturing groups private static void group(){ String str = "drfajian"; Pattern p1 = Pattern.compile("[a-z]{3}(?=a)"); Pattern p2 = Pattern.compile("(?=a)[a-z]{3}"); Pattern p3 = Pattern.compile("[a-z]{3}(?!a)"); Pattern p4 = Pattern.compile("(?!a)[a-z]{3}"); Matcher m1 = p1.matcher(str); Matcher m2 = p2.matcher(str); Matcher m3 = p3.matcher(str); Matcher m4 = p4.matcher(str); while(m1.find()){ System.out.print(m1.group() + " "); } System.out.println(); while(m2.find()){ System.out.print(m2.group() + " "); } System.out.println(); while(m3.find()){ System.out.print(m3.group() + " "); } System.out.println(); while(m4.find()){ System.out.print(m4.group() + " "); } System.out.println(); } //back references 向前引用 private static void reference(){ String str1 = "3232"; String str2 = "322"; Pattern p1 = Pattern.compile("(\\d\\d)\\1"); Pattern p2 = Pattern.compile("(\\d(\\d))\\2"); Matcher m1 = p1.matcher(str1); Matcher m2 = p2.matcher(str2); System.out.println(m1.matches()); System.out.println(m2.matches()); } //flags的简写 private static void flags(){ Pattern p1 = Pattern.compile("java",Pattern.CASE_INSENSITIVE); Pattern p2 = Pattern.compile("(?i)(java)");//两种写法一样,?i表示打开标志位 Matcher m1 = p1.matcher("JAva"); Matcher m2 = p2.matcher("JAva"); System.out.println(m1.matches()); System.out.println(m2.matches()); } }
来源:https://www.cnblogs.com/yxfyg/p/12622875.html