正则表达式入门

入门

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));
}
相关推荐
XYiFfang1 天前
【MYSQL】SQL学习指南:从常见错误到高级函数与正则表达式
sql·mysql·正则表达式·regexp_like·group_concat
czhc11400756633 天前
Linux108 shell:.bashrc 正则表达式:. * .* ^ $ ^$ [ ] [^] ^[] ^[^ ] \< \>
linux·正则表达式
数据知道3 天前
Go基础:正则表达式 regexp 库详解
开发语言·mysql·golang·正则表达式·go语言
利刃大大3 天前
【高并发服务器】三、正则表达式的使用
服务器·c++·正则表达式·项目
尘觉6 天前
正则表达式入门与进阶(优化版)
正则表达式
AI悦创|编程1v17 天前
00-1-正则表达式学习心得:从入门到上瘾,再到克制
数据仓库·正则表达式·数据挖掘·ai悦创编程一对一教学·python一对一辅导·python一对一教学
带土17 天前
PHP 中的正则表达式
正则表达式·php
taller_20008 天前
VBA之正则表达式(45)-- 拆分材料和规格
正则表达式·正则·数据清洗·提取数据·材料规格
光明磊8 天前
正则表达式Regex
正则表达式