入門
1、提取文章中所有的英文單詞
//1.先創建一個Pattern對象,模式對象,可以理解成就是一個正則表達式對象
Pattern pattern = Pattern.compile("[a-zA-Z]+");
//2.創建一個匹配器對象
//理解:就是 matcher匹配器按照pattern(模式/樣式),到 content文本中去匹配
//找到就返回true,否則就返回false
Matcher matcher = pattern.matcher(content);
//3,可以開始循環匹配
while (matcher.find()){//匹配內容,文本,放到 m.group(0)System.out.println("找到:" +matcher. group(0));
}
2、提取文章中所有的數字
把上述的匹配器改成:
Pattern pattern = Pattern.compile("[0-9]+");
3、提取文章中所有的英文單詞和數字
Pattern pattern = Pattern.compile("([0-9]+)|([a-zA-Z]+)");
4、提取百度熱榜標題
Pattern pattern = Pattern.compile(" <a target=\"_blank\" title=\"(\\S*)\"");
5、提取IP地址
Pattern pattern = Pattern.compile("\\d+\\.\\d+\\.\\d+\\.\\d");
測試
- 一段文本,找出所有四個數字連在一起的子串
//1. \\d 表示一個任意的數字
String regStr = "\\d\\d\\d\\d"
//2. 創建模式對象[即正則表達式對象]
Pattern pattern = Pattern.compile(regStr);
//3. 創建匹配器
//說明:創建匹配器 matcher, 按照 正則表達式的規則 去匹配 content 字符串
Matcher matcher = pattern.matcher(content);
// 4. 開始匹配
/*** matcher.find() 完成的任務 (考慮分組)* 什么是分組,比如 (\d\d)(\d\d) ,正則表達式中有() 表示分組,第 1 個()表示第 1 組,第 2 個()表示第 2 組...* 1. 根據指定的規則 ,定位滿足規則的子字符串(比如(19)(98))* 2. 找到后,將 子字符串的開始的索引記錄到 matcher 對象的屬性 int[] groups;* 2.1 groups[0] = 0 , 把該子字符串的結束的索引+1 的值記錄到 groups[1] = 4* 2.2 記錄 1 組()匹配到的字符串 groups[2] = 0 groups[3] = 2* 2.3 記錄 2 組()匹配到的字符串 groups[4] = 2 groups[5] = 4* 2.4.如果有更多的分組.....* 3. 同時記錄 oldLast 的值為 子字符串的結束的 索引+1 的值即 35, 即下次執行 find 時,就從 35 開始匹配**//**matcher.group(0) 分析** 源碼:* public String group(int group) {* if (first < 0)* throw new IllegalStateException("No match found");* if (group < 0 || group > groupCount())* throw new IndexOutOfBoundsException("No group " + group);* if ((groups[group*2] == -1) || (groups[group*2+1] == -1))* return null;* return getSubSequence(groups[group * 2], groups[group * 2 + 1]).toString();* }* 1. 根據 groups[0]=31 和 groups[1]=35 的記錄的位置,從 content 開始截取子字符串返回* 就是 [31,35) 包含 31 但是不包含索引為 35 的位置** 如果再次指向 find 方法.仍然按照上面分析來執行*///小結
//1. 如果正則表達式有() 即分組
//2. 取出匹配的字符串規則如下
//3. group(0) 表示匹配到的子字符串
//4. group(1) 表示匹配到的子字符串的第 1 組字符串
//5. group(2) 表示匹配到的子字符串的第 2 組字符串
//6. ... 但是分組的數不能越界. System.out.println("找到: " + matcher.group(0));
System.out.println("第 1 組()匹配到的值=" + matcher.group(1));
System.out.println("第 2 組()匹配到的值=" + matcher.group(2))
while(matcher.find()) {System.out.println("找到:" + matcher.group(0));
}
- 【正則表達式專欄】