目錄
1.Arrays
1.1認識Arrays
?1.2Arrays的排序
?2.JDK8的新特性:Lambda表達式
2.1認識Lambda表達式
?2.2用Lambda表達式簡化代碼、省略規則
3.JDK8的新特性:方法引用(進一步簡化Lambda表達式)
3.1 靜態方法引用
3.2 實例方法引用
3.3 特定類型方法的引用
3.4 構造器引用
4.常見算法
4.1 冒泡?編輯
4.2 選擇排序
4.3 二分查找
5.正則表達式
5.1 概述
5.2 正則表達式書寫規則
?5.3 正則表達式案例
5.4 正則爬取內容
5.5 搜索、分割
1.Arrays
1.1認識Arrays
package com.itheima.d1_array;import java.util.Arrays;
import java.util.function.IntToDoubleFunction;public class ArraysDemo1 {public static void main(String[] args) {// 目標:掌握操作數組的工具類:Arrays的常見方法。// 1、返回數組內容: public static String toString(類型[] a)int[] arr = {11, 55, 33, 22, 98};//System.out.println(arr);//[I@10f87f48//數組默認返回的是地址String result = Arrays.toString(arr);//自動封裝好System.out.println(result);// 2、拷貝數組的內容到一個新的數組,并返回新數組// public static 類型[] copyOfRange(類型[] original, int from, int to)int arr2[] = Arrays.copyOfRange(arr,1,4);//包前不包后System.out.println(Arrays.toString(arr2));// 3、給數組擴容。// public static 類型[] copyOf(類型[] original, int newLength)int[] arr3 = Arrays.copyOf(arr, 10);System.out.println(Arrays.toString(arr3));// 4、修改數組中每個數據,再存入。double[] scores = {99.5, 90, 59.5, 78, 98, 55};//需求:為每個分數加分10分//第二個參數為接口類型的對象參數,但是接口不能直接new對象,所以需要用匿名內部類Arrays.setAll(scores, new IntToDoubleFunction() {@Overridepublic double applyAsDouble(int index) {return scores[index] + 10;}});System.out.println(Arrays.toString(scores));// 5、Arrays類提供的對數組進行排序的操作。Arrays.sort(scores);//升序排序(由小到大)System.out.println(Arrays.toString(scores));}
}
?1.2Arrays的排序
package com.itheima.d1_array;import java.util.Arrays;
import java.util.Comparator;public class ArraysDemo2 {public static void main(String[] args) {// 目標:給存儲對象的數組進行排序。Student[] students = new Student[4]; // students = [null, null, null, null]// 0 1 2 3students[0] = new Student("周芷若", 21, '女', 169.3);students[1] = new Student("殷素素", 38, '女', 172.2);students[2] = new Student("小昭", 19, '女', 168.5);students[3] = new Student("張無忌", 23, '男', 183.5);// 自定義排序規則方式一:讓對象所在的類實現比較規則接口Comparable,重寫compareTo方法,來指定比較規則。
// Arrays.sort(students);// 自定義排序規則方式二:sort存在重載的方法,支持自帶Comparator比較器對象來直接指定比較規則(優先)// public static <T> void sort(T[] a, Comparator<? super T> c)Arrays.sort(students, new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {// return o1.getAge() - o2.getAge(); // 升序//那么如果要按照身高來進行排序呢?//return o1.getHeight() - o2.getHeight();//報錯,因為height是double類型,而方法的返回值類型是int
// if(o1.getHeight() > o2.getHeight()){
// return 1;
// }else if(o1.getHeight() < o2.getHeight()){
// return -1;
// }
// return 0;return Double.compare(o1.getHeight(), o2.getHeight());}});System.out.println(Arrays.toString(students));}
}
package com.itheima.d1_array;
// 自定義排序規則方式一:讓對象所在的類實現比較規則接口Comparable,重寫compareTo方法,來指定比較規則。
public class Student implements Comparable<Student>{private String name;private int age;private char gender;private double height;public Student() {}public Student(String name, int age, char gender, double height) {this.name = name;this.age = age;this.gender = gender;this.height = height;}// 指定大小規則// 比較者:this// 被比較者:o@Overridepublic int compareTo(Student o) {/*** 官方規定:* 如果您認為左邊大于右邊,請返回正整數。* 如果您認為左邊小于右邊,請返回負整數。* 如果您認為左邊等于右邊,請返回0。* 只要這么干,默認就是升序排序*/
// if(this.age > o.age) {
// return 1;
// }else if(this.age < o.age) {
// return -1;
// }
// return 0;//return this.age - o.age; // 升序。return o.age - this.age; // 降序。}/*** 獲取* @return name*/public String getName() {return name;}/*** 設置* @param name*/public void setName(String name) {this.name = name;}/*** 獲取* @return age*/public int getAge() {return age;}/*** 設置* @param age*/public void setAge(int age) {this.age = age;}/*** 獲取* @return gender*/public char getGender() {return gender;}/*** 設置* @param gender*/public void setGender(char gender) {this.gender = gender;}/*** 獲取* @return height*/public double getHeight() {return height;}/*** 設置* @param height*/public void setHeight(double height) {this.height = height;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +", gender=" + gender +", height=" + height +'}' + "\n";}}
?2.JDK8的新特性:Lambda表達式
2.1認識Lambda表達式
package com.itheima.d2_lambda;public class LambdaTest1 {public static void main(String[] args) {// 目標:認識Lambda是如何簡化匿名內部類的。Animal a1 = new Animal() {@Overridepublic void run() {System.out.println("🐅跑的賊快~~~~");}};a1.run();// 錯誤示范:Lambda并不能簡化所有匿名內部類的代碼。只能簡化函數式接口的匿名內部類。
// Animal a2 = () -> {
// System.out.println("🐅跑的賊快~~~~");
// };
// a2.run();Swimming s1 = new Swimming() {@Overridepublic void swim() {System.out.println("學生🏊?賊溜~~~~");}};s1.swim();// Lambda可以簡化函數式接口的匿名內部類// 可以簡化的原因:可以上下文推斷出真實的代碼形式!Swimming s2 = () -> {System.out.println("老師🏊?賊溜~~~~");};s2.swim();}
}@FunctionalInterface // 函數式接口中有且僅有一個抽象方法
interface Swimming{void swim();
}abstract class Animal{public abstract void run();
}
?2.2用Lambda表達式簡化代碼、省略規則
import com.itheima.d1_array.Student;import java.util.Arrays;
import java.util.Comparator;
import java.util.function.IntToDoubleFunction;public class LambdaTest2 {public static void main(String[] args) {// 目標:掌握Lambda表達式簡化常見函數式接口的匿名內部類double[] scores = {99.5, 90, 59.5, 78, 98, 55};// 需求:為每個分數加分10分。Arrays.setAll(scores, new IntToDoubleFunction() {@Overridepublic double applyAsDouble(int index) {return scores[index] + 10;}});Arrays.setAll(scores, (int index) -> {return scores[index] + 10;});Arrays.setAll(scores, (index) -> {return scores[index] + 10;});Arrays.setAll(scores, index -> {return scores[index] + 10;});Arrays.setAll(scores, index -> scores[index] + 10 );System.out.println(Arrays.toString(scores));System.out.println("---------------------------------------------------------------------");Student[] students = new Student[4]; // students = [null, null, null, null]// 0 1 2 3students[0] = new Student("周芷若", 21, '女', 169.3);students[1] = new Student("殷素素", 38, '女', 172.2);students[2] = new Student("小昭", 19, '女', 168.5);students[3] = new Student("張無忌", 23, '男', 183.5);Arrays.sort(students, new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {return Double.compare(o1.getHeight(), o2.getHeight());}});Arrays.sort(students, (Student o1, Student o2) -> {return Double.compare(o1.getHeight(), o2.getHeight());});Arrays.sort(students, (o1, o2) -> {return Double.compare(o1.getHeight(), o2.getHeight());});Arrays.sort(students, (o1, o2) -> Double.compare(o1.getHeight(), o2.getHeight()));System.out.println(Arrays.toString(students));}
}
3.JDK8的新特性:方法引用(進一步簡化Lambda表達式)
3.1 靜態方法引用
package com.itheima.d3_method_reference;public class Student implements Comparable<Student>{private String name;private int age;private char gender;private double height;//在Student類里寫一個靜態方法,用來通過身高比較public static int compareByHeight(Student o1, Student o2){return Double.compare(o1.getHeight(), o2.getHeight());}public Student() {}public Student(String name, int age, char gender, double height) {this.name = name;this.age = age;this.gender = gender;this.height = height;}// s1.compareTo(s2)// 比較者:s1 == this// 被比較者:s2 == o@Overridepublic int compareTo(Student o) {return this.age - o.age; // 升序}/*** 獲取* @return name*/public String getName() {return name;}/*** 設置* @param name*/public void setName(String name) {this.name = name;}/*** 獲取* @return age*/public int getAge() {return age;}/*** 設置* @param age*/public void setAge(int age) {this.age = age;}/*** 獲取* @return gender*/public char getGender() {return gender;}/*** 設置* @param gender*/public void setGender(char gender) {this.gender = gender;}/*** 獲取* @return height*/public double getHeight() {return height;}/*** 設置* @param height*/public void setHeight(double height) {this.height = height;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +", gender=" + gender +", height=" + height +'}' + "\n";}}
import java.util.Arrays;public class Test1 {public static void main(String[] args) {// 目標:理解靜態方法引用。Student[] students = new Student[4]; // students = [null, null, null, null]students[0] = new Student("周芷若", 21, '女', 169.3);students[1] = new Student("殷素素", 38, '女', 172.2);students[2] = new Student("小昭", 19, '女', 168.5);students[3] = new Student("張無忌", 23, '男', 183.5);// Arrays.sort(students, (o1, o2) -> Double.compare(o1.getHeight(), o2.getHeight()));//完全夠用
//
// Arrays.sort(students, (o1, o2) -> Student.compareByHeight(o1, o2));// 靜態方法引用。Arrays.sort(students, Student::compareByHeight); // 終極簡化代碼!System.out.println(Arrays.toString(students));}
}
3.2 實例方法引用
import java.util.Arrays;public class Test2 {public static void main(String[] args) {// 目標:理解實例方法引用。Student[] students = new Student[4]; // students = [null, null, null, null]students[0] = new Student("周芷若", 21, '女', 169.3);students[1] = new Student("殷素素", 38, '女', 172.2);students[2] = new Student("小昭", 19, '女', 168.5);students[3] = new Student("張無忌", 23, '男', 183.5);// Arrays.sort(students, (o1, o2) -> Double.compare(o1.getHeight(), o2.getHeight()));//要先創建對象Test2 t = new Test2();// Arrays.sort(students, (o1, o2) -> t.compare(o1, o2));Arrays.sort(students, t::compare);//還可以更簡潔//Arrays.sort(students, new Test2()::compare);System.out.println(Arrays.toString(students));}//定義一個對象方法public int compare(Student o1, Student o2){return Double.compare(o1.getHeight(), o2.getHeight());}
}
3.3 特定類型方法的引用
import java.util.Arrays;
import java.util.Comparator;public class Test3 {public static void main(String[] args) {// 目標:特定類型的方法引用。String[] names = {"dlei", "Angela", "baby", "caocao", "Coach", "曹操" ,"deby", "eason", "andy"};// 對他們排序(默認按照首字母編號排序)// 拓展(忽略大小寫排序)
// Arrays.sort(names, new Comparator<String>() {
// @Override
// public int compare(String o1, String o2) {
// // o1 Angela
// // o2 andy
// return o1.compareToIgnoreCase(o2);
// }
// });
//
// Arrays.sort(names, ( o1, o2) -> o1.compareToIgnoreCase(o2));Arrays.sort(names, String::compareToIgnoreCase);System.out.println(Arrays.toString(names));}
}
3.4 構造器引用
public class Test4 {public static void main(String[] args) {// 目標:掌握構造器引用。
// Create c1 = new Create() {
// @Override
// public Car createCar(String name) {
// return new Car(name);
// }
// };// Create c1 = name -> new Car(name) ;Create c1 = Car::new;//硬造場景,實際上Car car = new Car("布加迪威龍");就可以了Car car = c1.createCar("布加迪威龍");System.out.println(car);}
}@FunctionalInterface // 函數式接口
interface Create{//用來創建一個Car對象,Car對象的名字是nameCar createCar(String name);
}//硬造場景,沒有意義,用來理解語法
//先定義一個Car類
class Car{private String name;public Car() {}public Car(String name) {this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "Car{" +"name='" + name + '\'' +'}';}
}
4.常見算法
4.1 冒泡
import java.util.Arrays;public class Demo1 {public static void main(String[] args) {// 目標:完成冒泡排序的代碼實現。// 1、定義一個數組int[] arr = {5, 2, 3, 1};// 0 1 2 3// 2、定義一個循環控制冒幾輪.for (int i = 0; i < arr.length - 1; i++) {// 輪數(i) 每輪的次數 j的占位// 第一輪0 3 0 1 2// 第二輪1 2 0 1// 第三輪2 1 0// 3、內部循環要控制每輪比較幾次for (int j = 0; j < arr.length - i - 1; j++) {// 4、判斷當前位置j是否大于其后一個位置處的數據,若較大,則交換。if(arr[j] > arr[j+1]){// 5、定義一個臨時變量記住后一個位置處的數據int temp = arr[j+1];// 6、把前一個位置處的數據賦值給后一個位置處arr[j+1] = arr[j];// 7、把后一個位置原來的數據賦值給前一個位置處arr[j] = temp;}}}System.out.println(Arrays.toString(arr));}
}
4.2 選擇排序
package com.itheima.d4_sf;import java.util.Arrays;public class Demo2 {public static void main(String[] args) {// 目標:實現選擇排序。// 1、定義一個數組int[] arr = {5, 1, 3, 2};// 0 1 2 3// 2、定義一個循環控制選擇幾輪。for (int i = 0; i < arr.length - 1; i++) {/**輪數(i) 次數 j的占位0 3 1 2 31 2 2 32 1 3*/// 3、內部循環控制選擇幾次。for (int j = i + 1; j < arr.length; j++) {// 4、判斷j對應位置處的數據是否小于當前i位置處的數據,若較小則交換。if(arr[i] > arr[j]) {int temp = arr[j];arr[j] = arr[i];arr[i] = temp;}}}System.out.println(Arrays.toString(arr));}
}
?這種寫法會造成數組頻繁的交換,性能不好,有沒有更優的寫法呢?
package com.itheima.d4_sf;import java.util.Arrays;public class Demo2_2 {public static void main(String[] args) {// 目標:實現選擇排序。// 1、定義一個數組int[] arr = {5, 1, 3, 2};// 0 1 2 3// 2、定義一個循環控制選擇幾輪。for (int i = 0; i < arr.length - 1; i++) {/**輪數(i) 次數 j的占位0 3 1 2 3但是1 2 2 32 1 3*/// 定義一個變量記住本輪最小值對應的索引int min = i;// 3、內部循環控制選擇幾次。for (int j = i + 1; j < arr.length; j++) {// 4、判斷j對應位置處的數據是否小于當前min位置處的數據,若較小則交換min為j值。//也就是找出索引i后面最小的數字與i進行交換,把最小的數字換到i的位置if(arr[j] < arr[min]) {min = j;}}//5.如果在本輪中找到了比當前索引i處更小的元素(即min != i),則交換這兩個元素。if(min != i){int temp = arr[i];arr[i] = arr[min];arr[min] = temp;}}System.out.println(Arrays.toString(arr));}
}
4.3 二分查找
package com.itheima.d4_sf;public class Demo3 {public static void main(String[] args) {// 目標:完成二分查找算法。int[] array = {7, 23, 79, 81, 103, 127, 131, 147};int index = searchDataIndex(array, 79);System.out.println("79的索引是:" + index);int index2 = searchDataIndex(array, 179);System.out.println("179的索引是:" + index2);}public static int searchDataIndex(int[] array, int number){// array = {7, 23, 79, 81, 103, 127, 131, 147}// 1、定義頭尾指針int left = 0;int right = array.length - 1;// 2、開始折半查詢。while (left <= right) {// 3、取中間索引int middle = (left + right) / 2;// 4、判斷當前要找的數據,與中間位置處的數據大小情況if(number > array[middle]) {// 5、往右邊找,左邊指針更新為 = 中間位置 + 1.left = middle + 1;}else if(number < array[middle]) {// 6、往左邊找,右邊指針更新為 = 中間位置-1right = middle - 1;}else {return middle;}}return -1;}
}
5.正則表達式
5.1 概述
5.2 正則表達式書寫規則
預定義字符(只能匹配單個字符) :? \d? \D?? \s? \S? \w? \W
在Java中,\是有特殊用途的,一般作為特殊字符使用不能獨立存在:\n 代表換行? ?\t 代表一個空格縮進
?所以在使用預定義字符時 \d 等需要再使用 \ 轉義
package com.itheima.d5_regex;/*** 目標:掌握正則表達式的書寫規則*/
public class RegexTest2 {public static void main(String[] args) {// 1、字符類(只能匹配單個字符)System.out.println("a".matches("[abc]")); // [abc]只能匹配a、b、cSystem.out.println("e".matches("[abcd]")); // falseSystem.out.println("d".matches("[^abc]")); // [^abc] 不能是abcSystem.out.println("a".matches("[^abc]")); // falseSystem.out.println("b".matches("[a-zA-Z]")); // [a-zA-Z] 只能是a-z A-Z的字符System.out.println("2".matches("[a-zA-Z]")); // falseSystem.out.println("k".matches("[a-z&&[^bc]]")); // : a到z,除了b和cSystem.out.println("b".matches("[a-z&&[^bc]]")); // falseSystem.out.println("ab".matches("[a-zA-Z0-9]")); // false 注意:以上帶 [內容] 的規則都只能用于匹配單個字符// 2、預定義字符(只能匹配單個字符) . \d \D \s \S \w \WSystem.out.println("徐".matches(".")); // .可以匹配任意字符System.out.println("徐徐".matches(".")); // false,因為只能匹配一個字符// 在Java中,\是有特殊用途的,一般作為特殊字符使用不能獨立存在:\n代表換行 \t代表一個空格縮進// \需要再使用\轉義System.out.println("2".matches("\\d")); // true \d:代表數字0-9 \D:代表非數字System.out.println("a".matches("\\d")); // falseSystem.out.println(" ".matches("\\s")); // \s: 代表一個空白字符System.out.println("a".matches("\s")); // falseSystem.out.println("a".matches("\\S")); // \S: 代表一個非空白字符System.out.println(" ".matches("\\S")); // falseSystem.out.println("a".matches("\\w")); // \w: [a-zA-Z_0-9]System.out.println("_".matches("\\w")); // trueSystem.out.println("徐".matches("\\w")); // falseSystem.out.println("徐".matches("\\W")); // [^\w]不能是a-zA-Z_0-9System.out.println("a".matches("\\W")); // falseSystem.out.println("23232".matches("\\d")); // false 注意:以上預定義字符都只能匹配單個字符。// 3、數量詞: ? * + {n} {n, } {n, m}System.out.println("a".matches("\\w?")); // ? 代表0次或1次System.out.println("".matches("\\w?")); // trueSystem.out.println("abc".matches("\\w?")); // falseSystem.out.println("abc12".matches("\\w*")); // * 代表0次或多次System.out.println("".matches("\\w*")); // trueSystem.out.println("abc12張".matches("\\w*")); // falseSystem.out.println("abc12".matches("\\w+")); // + 代表1次或多次System.out.println("".matches("\\w+")); // falseSystem.out.println("abc12張".matches("\\w+")); // falseSystem.out.println("a3c".matches("\\w{3}")); // {3} 代表要正好是n次System.out.println("abcd".matches("\\w{3}")); // falseSystem.out.println("abcd".matches("\\w{3,}")); // {3,} 代表是>=3次System.out.println("ab".matches("\\w{3,}")); // falseSystem.out.println("abcde徐".matches("\\w{3,}")); // falseSystem.out.println("abc232d".matches("\\w{3,9}")); // {3, 9} 代表是 大于等于3次,小于等于9次// 4、其他幾個常用的符號:(?i)忽略大小寫 、 或:| 、 分組:()System.out.println("----------------------------------------------------");System.out.println("abc".matches("(?i)abc")); // trueSystem.out.println("ABC".matches("(?i)abc")); // trueSystem.out.println("aBc".matches("a((?i)b)c")); // trueSystem.out.println("ABc".matches("a((?i)b)c")); // false// 需求1:要求要么是3個小寫字母,要么是3個數字。System.out.println("123".matches("(\\d{3})|([a-z]{3})"));//trueSystem.out.println("abc".matches("(\\d{3})|([a-z]{3})"));//trueSystem.out.println("ab1".matches("(\\d{3})|([a-z]{3})"));//false// 需求2:必須是”我愛“開頭,中間可以是至少一個”編程“,最后至少是1個”666“System.out.println("我愛編程編程666666".matches("我愛(編程)+(666)+"));//trueSystem.out.println("我愛編程編程6666666".matches("我愛(編程)+(666)+"));//false一定要3個666}
}
?5.3 正則表達式案例
需求:校驗用戶輸入的電話、郵箱、時間是否合法
shift + F6 給相同的名稱重新命名
package com.itheima.d5_regex;import java.util.Scanner;public class RegexTest3 {public static void main(String[] args) {// 目標:使用所學的正則表達式來校驗數據的合法性。//checkEmail();checkPhone();}public static void checkPhone(){while (true) {Scanner sc = new Scanner(System.in);System.out.println("請您輸入手機號碼:");String phone = sc.next();if(phone.matches("1[3-9]\\d{9}")) {System.out.println("手機號碼合法,錄入成功!");break;}else {System.out.println("您輸入的手機號碼有毛病!請重新輸入!");}}}public static void checkEmail(){while (true) {Scanner sc = new Scanner(System.in);System.out.println("請您輸入郵箱:");String email = sc.next();// dlei0009@163.com// 5423253@qq.com// xulei2@itcast.com.cnif(email.matches("\\w{2,30}@\\w{2,20}(\\.\\w{2,30}){1,2}")) {System.out.println("郵箱合法,錄入成功!");break;}else {System.out.println("您輸入的郵箱有毛病!請重新輸入!");}}}}
5.4 正則爬取內容
第一個案例:
package com.itheima.d5_regex;import java.util.regex.Matcher;
import java.util.regex.Pattern;public class RegexTest4 {public static void main(String[] args) {// 目標:了解使用正則表達式去文本中爬取想要的信息。String data = "來黑馬程序員學習Java,\n" +"電話:18512516758,18512508907\n" +"或者聯系郵箱: boniu@itcast.cn\n" +"座機電話:01036517895,010-98951256\n" +"郵箱:bozai@itcast.cn,\n" +"郵箱2:dlei0009@163.com,\n" +"熱線電話:400-618-9090 ,400-618-4000,\n" +"4006184000,4006189090\n";// 需求:從中間爬取出郵箱 手機號碼 座機號碼 400號碼。// 1、定義爬取規則對象,封裝要爬取的格式。//這是官方規定的格式去編譯我們所寫的爬取規則,來得到一個爬取規則對象Pattern pattern = Pattern.compile("(\\w{2,30}@\\w{2,20}(\\.\\w{2,20}){1,2})|(1[3-9]\\d{9})" +"|(0\\d{2,6}-?[1-9]\\d{3,10})|(400-?[1-9]\\d{2,6}-?[1-9]\\d{2,6})");// 2、通過匹配規則對象pattern與內容data建立聯系得到一個匹配器對象//匹配器對象可以拿到匹配規則pattern去提供的數據data中爬取內容Matcher matcher = pattern.matcher(data);// 3、使用匹配器對象,開始爬取內容。//matcher.find()的返回值類型是boolean,如果返回為true就說明爬取到符合規則的內容while (matcher.find()){String info = matcher.group();System.out.println(info);}}
}
第二個案例:
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class RegexTest5 {public static void main(String[] args) {// 目標:了解使用正則表達式去文本中爬取想要的信息。(分組爬取)String data = "來黑馬程序員學習Java,\n" +"電話:18512516758,18512508907\n" +"或者聯系郵箱: boniu@itcast.cn\n" +"座機電話:01036517895,010-98951256\n" +"郵箱:bozai@itcast.cn,\n" +"郵箱2:dlei0009@163.com,\n" +"熱線電話:400-618-9090 ,400-618-4000,\n" +"4006184000,4006189090\n";// 1、指定爬取規則對象:設置匹配規則。//用分組爬取,把郵箱前面的部分括起來代表第一組Pattern p = Pattern.compile("(\\w{2,30})@\\w{2,20}(\\.\\w{2,20}){1,2}");// 2、讓內容和爬取規則建立關系,得到一個匹配器對象。Matcher matcher = p.matcher(data);// 3、開始使用匹配器對象,開始爬取內容while (matcher.find()) {// 把爬到的信息提取出來String rs = matcher.group(1); // 只要爬取出來的郵箱中的第一組括號的內容。System.out.println(rs);}}
}
?第三個案例:
?
package com.itheima.d5_regex;import java.util.regex.Matcher;
import java.util.regex.Pattern;public class RegexTest6 {public static void main(String[] args) {// 目標:了解使用正則表達式去文本中爬取想要的信息。(了解)String data = "歡迎張全蛋光臨本系統!他刪庫并跑路歡迎李二狗子光臨本系統!" +" 歡迎馬六子光臨本系統!它瀏覽了很多好看的照片!歡迎夏洛光臨本系統!他在六點鐘送出了一個嘉年華!" ;// 1、指定爬取規則對象:設置匹配規則。//(.+)代表中間的名字可以是任意個
// String regex1 = "歡迎(.+)光臨"; // 貪婪匹配! 最大范圍匹配:從第一個歡迎匹配到最后一個光臨String regex2 = "歡迎(.+?)光臨"; // 非貪婪匹配 最小范圍匹配(規定,也可以理解為?代表0或1次)Pattern p = Pattern.compile(regex2);// 2、讓內容和爬取規則建立關系,得到一個匹配器對象。Matcher matcher = p.matcher(data);// 3、開始使用匹配器對象,開始爬取內容while (matcher.find()) {// 把爬到的信息提取出來String rs = matcher.group(1); // 我只要爬取內容中的第一組()內容System.out.println(rs);}}
}
?組的編號規則:組號是按照左括號出現的順序來確定的,從1開始計數
特殊組號0:組號0代表的是整個正則表達式所匹配的內容,組0對應的就是“歡迎張全蛋光臨”這樣完整的內容
而組1也就是(.+?),他匹配的是兩個關鍵詞之間的任意字符,如“張全蛋”就是組1匹配的內容,會把所有滿足條件的內容都輸出
5.5 搜索、分割
import java.util.Arrays;/*** 目標:了解使用正則表達式做搜索替換,內容分割。*/
public class RegexTest7 {public static void main(String[] args) {// 1、public String replaceAll(String regex , String newStr):按照正則表達式匹配的內容進行替換// 需求1:請把 古力娜扎ai8888迪麗熱巴999aa5566馬爾扎哈fbbfsfs42425卡爾扎巴,中間的非中文字符替換成 “-”String s1 = "古力娜扎ai8888迪麗熱巴99fafas9aa5566馬爾扎哈fbbADFFfsfs42425卡爾扎巴";//\w+代表一次或多次英文字母,數字或下劃線String result = s1.replaceAll("\\w+", "-");System.out.println(result);// 2、public String[] split(String regex):按照正則表達式匹配的內容進行分割字符串,反回一個字符串數組。// 需求1:請把 古力娜扎ai8888迪麗熱巴999aa5566馬爾扎哈fbbfsfs42425卡爾扎巴,中的人名獲取出來。String[] names = s1.split("\\w+");for (int i = 0; i < names.length; i++) {System.out.println(names[i]);}}
}
?