Java正则表达式
时间:2022-07-25
本文章向大家介绍Java正则表达式,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
Java正则表达式时不时的用一下,虽然可以解决问题,总是没有完全弄明白其中的一些接口的含义。本文熟悉了相关的几个常见接口。
匹配
- 直接匹配
String content = "hello world 1, hello world 2, hello world 3, hello world 100.";
Pattern.matches("hello world (\d+)", content);
- 预编译
public class App {
private static final Pattern PATTERN = Pattern.compile("hello world (\d+)");
public static void main(String[] args) {
String content = "hello world 1, hello world 2, hello world 3, hello world 100.";
Matcher matcher = PATTERN.matcher(content);
System.out.println(matcher.matches());
}
}
捕获组
捕获组是通过从左至右计算其开括号来编号。例如,在表达式((A)(B(C))),有四个这样的组:
- ((A)(B(C)))
- (A)
- (B(C))
- (C)
可以通过调用 matcher 对象的 groupCount 方法来查看表达式有多少个分组。groupCount 方法返回一个 int 值,表示matcher对象当前有多个捕获组。
还有一个特殊的组(group(0)),它总是代表整个表达式。该组不包括在 groupCount 的返回值中。
- 捕获实例(if (matcher.find()))
public class App {
private static final Pattern PATTERN = Pattern.compile("hello (world (\d+))");
public static void main(String[] args) {
String content = "hello world 1, hello world 2, hello world 3, hello world 100.";
Matcher matcher = PATTERN.matcher(content);
if (matcher.find()) {
for (int i = 0; i <= matcher.groupCount(); i++) {
System.out.println(matcher.group(i));
}
}
}
}
- 输出
hello world 1
world 1
1
匹配多个(while (matcher.find()))
public class App {
private static final Pattern PATTERN = Pattern.compile("hello (world (\d+))");
public static void main(String[] args) {
String content = "hello world 1, hello world 2, hello world 3, hello world 100.";
Matcher matcher = PATTERN.matcher(content);
// 找到所有匹配字符串
while (matcher.find()) {
// 输出所有的匹配组
for (int i = 0; i <= matcher.groupCount(); i++) {
System.out.println(matcher.group(i));
}
}
}
}
- 输出
hello world 1
world 1
1
hello world 2
world 2
2
hello world 3
world 3
3
hello world 100
world 100
100
- java教程
- Java快速入门
- Java 开发环境配置
- Java基本语法
- Java 对象和类
- Java 基本数据类型
- Java 变量类型
- Java 修饰符
- Java 运算符
- Java 循环结构
- Java 分支结构
- Java Number类
- Java Character类
- Java String类
- Java StringBuffer和StringBuilder类
- Java 数组
- Java 日期时间
- Java 正则表达式
- Java 方法
- Java 流(Stream)、文件(File)和IO
- Java 异常处理
- Java 继承
- Java 重写(Override)与重载(Overload)
- Java 多态
- Java 抽象类
- Java 封装
- Java 接口
- Java 包(package)
- Java 数据结构
- Java 集合框架
- Java 泛型
- Java 序列化
- Java 网络编程
- Java 发送邮件
- Java 多线程编程
- Java Applet基础
- Java 文档注释
- yii2 url重写并隐藏index.php方法
- PHP设计模式之模板方法模式实例浅析
- keras 自定义loss model.add_loss的使用详解
- keras做CNN的训练误差loss的下降操作
- Python基于yaml文件配置logging日志过程解析
- Python ckeditor富文本编辑器代码实例解析
- PHP自定义错误处理的方法分析
- PHP聊天室简单实现方法详解
- phpStorm+XDebug+chrome 配置详解
- PHP面向对象程序设计之多态性的应用示例
- PHP设计模式之单例模式定义与用法分析
- PHP面向对象程序设计之接口的继承定义与用法详解
- PHP简单验证码功能机制实例详解
- php高清晰度无损图片压缩功能的实现代码
- Python自省及反射原理实例详解