正则表达式入门

入门

1、提取文章中所有的英文单词

java 复制代码
//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、提取文章中所有的数字

把上述的匹配器改成:

java 复制代码
Pattern pattern = Pattern.compile("[0-9]+");

3、提取文章中所有的英文单词和数字

java 复制代码
Pattern pattern = Pattern.compile("([0-9]+)|([a-zA-Z]+)");

4、提取百度热榜标题

java 复制代码
Pattern pattern = Pattern.compile(" <a target=\"_blank\" title=\"(\\S*)\"");

5、提取IP地址

java 复制代码
Pattern pattern = Pattern.compile("\\d+\\.\\d+\\.\\d+\\.\\d");

测试

  1. 一段文本,找出所有四个数字连在一起的子串
java 复制代码
//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));
}
相关推荐
旭日东升的xu.2 天前
Python(09)正则表达式
正则表达式
程序员编程指南3 天前
Qt字符串处理与正则表达式应用
c语言·c++·qt·正则表达式
王柏龙3 天前
正则表达式 \b:单词边界
正则表达式
钮钴禄·爱因斯晨7 天前
Java API (二):从 Object 类到正则表达式的核心详解
java·开发语言·信息可视化·正则表达式
愈努力俞幸运8 天前
python 正则表达式
正则表达式
PythonicCC9 天前
Python正则表达式
python·正则表达式
木子杳衫10 天前
【Python】LEGB作用域 + re模块 + 正则表达式
数据库·python·正则表达式
MediaTea10 天前
Python 库手册:re 正则表达式模块
开发语言·python·正则表达式
m0dw13 天前
正则表达式梳理
正则表达式
mortimer14 天前
Python 正则替换陷阱:`\1` 为何变成了 `\x01`?
python·正则表达式