Java中“匹配”指用正则表达式模式匹配字符串,主要通过Pattern和Matcher类实现。1. Pattern编译正则,Matcher执行匹配,如提取邮箱;2. Matcher提供matches()、find()、group()等方法进行全串或子串匹配;3. String类支持matches()、replaceAll()、split()等便捷操作;4. 正则分组可捕获子表达式内容,通过group(n)获取;需注意转义、性能及贪婪匹配细节。

在 Java 中,"匹配" 通常指的是使用正则表达式(Regular Expression)对字符串进行模式匹配。Java 提供了 java.util.regex 包来支持正则表达式的操作,主要涉及两个类:Pattern 和 Matcher,以及一个便捷类 String 中的匹配方法。
1. Pattern 和 Matcher 的基本用法
Pattern 是正则表达式的编译表示形式,而 Matcher 是用来对目标字符串进行匹配操作的实际引擎。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String[] args) {
String text = "Contact us at support@example.com or sales@example.org";
String regex = "\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println("找到邮箱: " + matcher.group());
}
}
}
这段代码会输出:
找到邮箱: support@example.com找到邮箱: sales@example.org
2. Matcher 的常用方法
Matcher 类提供多个用于匹配的方法:
立即学习“Java免费学习笔记(深入)”;
- matches():判断整个字符串是否完全匹配正则表达式。
- find():查找输入序列中与模式匹配的下一个子序列。
- lookingAt():从输入序列的起始位置开始尝试匹配,不要求匹配整个字符串。
- group():返回匹配到的子字符串。
- start() 和 end():返回当前匹配的起始和结束索引。
示例:
String input = "Age: 25";
String regex = "\\d+";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
if (m.matches()) {
// 不会执行,因为整个字符串不是纯数字
}
if (m.find()) {
System.out.println("找到数字: " + m.group()); // 输出: 25
}
3. String 类中的匹配方法
Java 的 String 类也提供了直接使用正则表达式的简便方法:
- boolean matches(String regex):检查整个字符串是否匹配指定正则表达式。
- String replaceAll(String regex, String replacement):替换所有匹配项。
- String[] split(String regex):按正则表达式分割字符串。
示例:
String phone = "123-456-7890";
if (phone.matches("\\d{3}-\\d{3}-\\d{4}")) {
System.out.println("电话格式正确");
}
String cleaned = phone.replaceAll("-", ""); // 结果: 1234567890
String[] parts = "apple,banana,cherry".split(","); // 分割成数组
4. 分组(Grouping)和捕获
正则表达式可以用括号 () 进行分组,Matcher 可以通过 group(int group) 获取捕获的内容。
String input = "John Doe (johndoe)";
String regex = "(\\w+)\\s+(\\w+)\\s+\\((\\w+)\\)";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
if (m.find()) {
System.out.println("姓: " + m.group(1)); // John
System.out.println("名: " + m.group(2)); // Doe
System.out.println("用户名: " + m.group(3)); // johndoe
}
基本上就这些。Java 的正则匹配功能强大,适合处理文本提取、验证、替换等任务。关键是掌握 Pattern、Matcher 的协作方式,并熟悉常用正则语法。实际使用时注意性能,频繁匹配建议复用 Pattern 对象。不复杂但容易忽略细节,比如转义字符和贪婪匹配。











