- Java 编程示例
- 示例 - 首页
- 示例 - 环境
- 示例 - 字符串
- 示例 - 数组
- 示例 - 日期和时间
- 示例 - 方法
- 示例 - 文件
- 示例 - 目录
- 示例 - 异常
- 示例 - 数据结构
- 示例 - 集合
- 示例 - 网络
- 示例 - 线程
- 示例 - 小程序
- 示例 - 简单 GUI
- 示例 - JDBC
- 示例 - 正则表达式
- 示例 - Apache PDF Box
- 示例 - Apache POI PPT
- 示例 - Apache POI Excel
- 示例 - Apache POI Word
- 示例 - OpenCV
- 示例 - Apache Tika
- 示例 - iText
- Java 教程
- Java - 教程
- 有用的 Java 资源
- Java - 快速指南
- Java - 有用资源
如何重置 Java 中的正则表达式模式
问题描述
如何重置正则表达式的模式
解决方案
以下示例演示如何使用 Pattern 类中的 Pattern.compile() 和 Matcher 类中的 m.find() 方法重置正则表达式的模式。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Resetting {
public static void main(String[] args) throws Exception {
Matcher m = Pattern.compile("[frb][aiu][gx]").matcher("fix the rug with bags");
while (m.find())System.out.println(m.group());
m.reset("fix the rig with rags");
while (m.find())System.out.println(m.group());
}
}
结果
上述代码示例将产生以下结果。
fix rug bag fix rig rag
以下是重置正则表达式模式的另一个示例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Matc {
public static void main(String args[]) {
Pattern p = Pattern.compile("\\d");
Matcher mat1 = p.matcher("9652018244");
while (mat1.find()) {
System.out.println("\t\t" + mat1.group());
}
mat1.reset();
System.out.println("After done resetting the Matcher, it should be like this");
while (mat1.find()) {
System.out.println("\t\t" + mat1.group());
}
}
}
结果
上述代码示例将产生以下结果。
9 6 5 2 0 1 8 2 4 4 After done resetting the Matcher, it should be like this 9 6 5 2 0 1 8 2 4 4
java_regular_exp.htm
广告