正则表达式(Regular Expression)是一种强大的文本处理工具,通过特定模式实现字符串的匹配、查找、替换和分割操作。Java通过java.util.regex包提供完整的正则支持。
// 编译正则表达式
Pattern pattern = Pattern.compile("\\d+");
// 创建匹配器
Matcher matcher = pattern.matcher("123abc");
// 进行匹配操作
boolean matches = matcher.matches();
Matcher matcher = pattern.matcher("test123text456");
while(matcher.find()) {
System.out.println("找到: " + matcher.group());
}
| 元字符 | 说明 | 示例 |
|---|---|---|
| . | 匹配任意字符 | a.c 匹配 abc |
| \d | 数字字符 | \d+ 匹配 123 |
| \w | 单词字符 | \w+ 匹配 hello |
| [] | 字符集合 | [abc] 匹配 a/b/c |
| ^ | 开始位置 | ^Java 匹配Java开头 |
| $ | 结束位置 | end$ 匹配end结尾 |
String emailRegex = "^[\\w.-]+@[\\w.-]+\\.[a-z]{2,}$";
boolean isValid = Pattern.matches(emailRegex, "test@example.com");
String phoneRegex = "^1[3-9]\\d{9}$";
Pattern.compile(phoneRegex).matcher("13800138000").matches();
String result = "Hello123World".replaceAll("\\d+", "_");
// 输出: Hello_World
Pattern p = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
Matcher m = p.matcher("2023-12-01");
if(m.find()) {
System.out.println("年: " + m.group(1)); // 2023
System.out.println("月: " + m.group(2)); // 12
System.out.println("日: " + m.group(3)); // 01
}
Q: 如何处理特殊字符转义?
A: 使用\\进行转义,如\\匹配反斜杠,\\.匹配点号
Q: 如何实现非贪婪匹配?
A: 在量词后加?,如.*?实现最小匹配
通过掌握这些正则表达式知识,您将能够高效处理各种文本匹配和提取需求,提升Java编程效率。