当前位置:网站首页>解析正则表达式(一)
解析正则表达式(一)
2022-07-29 16:14:00 【SSS4362】
解析正则表达式(一)
1 含义
文本处理的神器
2 作用
2.1 验证文本是否符合业务格式
如:邮箱的验证,判断用户注册时的邮箱是否符合格式,如果不合适,就不允许注册通过
2.1 筛选字符串
如:爬虫,如爬取b站或者百度上面的热搜排行榜信息
3.如何用
3.1 步骤(基本)
3.1.1 提供需要查找的字符串content
String content="查找的内容";
3.1.2 提供正则表达式模板字符串regStr
String regStr="模板格式"
//以这个模板字符串去进行匹配,如果找到了就获取并打印出来
3.1.3 创建正则表达式对象(使用静态的compile方法)
Pattern pattern=Pattern.compile(regStr);
3.1.4 创建匹配器对象
Matcher matcher=pattern.matcher(content);
3.1.5 通过matcher.find()和matcher.group(0)获取并打印符合模板字符串的字符串
matcher.find()为循环条件,matcher.group(0)为符合条件的每一个字符串
//本质还是用indexOf然后往下去截取,所以如果模板字符串长度大于查找字符串,那就没有查找的必要了
while(matcher.find()){
System.out.println("找到了"+matcher.group(0));
}
3.2 示例代码
//获取并打印字符串中所有连续的四个数字,用方法实现
package Work;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test05 {
public static void main(String[] args) {
//1.查找的字符串
String content="java1234djfb7890tetx7680ncuwi123";
//2.模板字符串
String regex="[\\d]{4}";
//3.创建正则表达式对象
Pattern pattern=Pattern.compile(regex);
//4.创建匹配器对象
Matcher matcher=pattern.matcher(content);
//5.获取并打印符合条件的字符串
while(matcher.find()){
System.out.println("找到了"+matcher.group(0));
}
}
}
3.3 示例代码运行截图

4.String类中的matcher方法
4.1 语法
字符串对象.matcher(regex);
//regex为模板字符串
4.2 核心内容
若原字符串符合模板字符串这个格式(位数需要一模一样),那么就返回true,返回false
4.3 示例代码
package Work;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test05 {
public static void main(String[] args) {
String content="1234";
String regex01="[\\d]{4}";
String regex02="[\\d]{3}";
System.out.println(content.matches(regex01));
System.out.println(content.matches(regex02));
//这个是需要匹配原来字符串和模板字符串一模一样(位数一样)才会返回true,否则返回false
}
}
4.4 示例代码运行截图

边栏推荐
猜你喜欢

HMS Core音频编辑服务音源分离与空间音频渲染,助力快速进入3D音频的世界

Knowledge Graph Construction of Mall Commodities

解析idea中的debug调试模式

pycaret在钻石数据集上的使用 - 回归问题

MLX90640 infrared thermal imager development notes (9)

两军交锋

(notes) Build the was configured to -- Settings repositories over project repositories but solutions

中小型金融企业该如何进行灾备建设?
![[PCL study notes] Commonly used libraries and APIs for point cloud processing (PCL library Eigen)](/img/b6/0f6113109aef776c777cb25a0ffb95.png)
[PCL study notes] Commonly used libraries and APIs for point cloud processing (PCL library Eigen)

澜舟孟子轻量化预训练模型技术实践
随机推荐
百面量化金融
flutter如何实现切换页面缓存
Greedy (1) interval complete coverage problem
pycaret在钻石数据集上的使用 - 回归问题
PHP使用PDO连接sql server
[极客大挑战 2019]LoveSQL 1
Knowledge Graph Construction of Mall Commodities
LinkedList 5-141. The circular linked list
贪心(1)区间完全覆盖问题
LinkedList 5-141. 环形链表
阶乘因式分解
wooden stick
GBJ2510-ASEMI电机专用25A整流桥GBJ2510
Chicken and rabbit in the same cage
mysql的sql分页查询语句怎么写_sql 分页查询语句(mysql分页语句)「建议收藏」
ASCII code sorting
58 security - image quality assessment technology practice
[Server Storage Data Recovery] A data recovery case of a RAID 5 crash caused by the failure of a certain model of Huawei OceanStor storage RAID 5 hard disk and the failure to synchronize data with the
2020年Mobileye收入近10亿美元,EyeQ芯片出货1930万颗
零花钱