Java正则表达式应用与知识点详解
一、正则表达式基础概念
正则表达式(Regular Expression)是通过特定语法规则描述字符串模式的工具,常用于:
- 数据格式验证
- 文本搜索与替换
- 字符串分割
- 模式匹配提取
Java通过java.util.regex
包提供支持,核心类:
Pattern
:编译后的正则表达式对象Matcher
:执行匹配操作的引擎PatternSyntaxException
:正则语法异常
二、核心语法详解
- 字符匹配
// 匹配数字字符
String regex = "\\d"; // 等效于[0-9]
System.out.println("8".matches(regex)); // true// 特殊字符转义
String regex2 = "\\$\\d+\\.\\d{2}"; // 匹配$12.34格式
System.out.println("$99.99".matches(regex2)); // true
-
预定义字符类 | 表达式 | 说明 | |--------|-----------------------| |
\d
| 数字:[0-9] | |\D
| 非数字:[^0-9] | |\s
| 空白字符:[\t\n\x0B\f\r] | |\w
| 单词字符:[a-zA-Z_0-9]| -
量词
String regex = "a{2,4}"; // 匹配2到4个a
System.out.println("aaa".matches(regex)); // true
- 边界匹配
// 匹配完整行
String regex = "^\\d{3}-\\d{4}$";
System.out.println("123-4567".matches(regex)); // true
三、分组与反向引用
Pattern pattern = Pattern.compile("(\\d{3})-(\\d{4})");
Matcher matcher = pattern.matcher("123-4567");
if(matcher.find()){System.out.println(matcher.group(0)); // 123-4567System.out.println(matcher.group(1)); // 123System.out.println(matcher.group(2)); // 4567
}
四、常用方法实战
- 字符串分割
String[] parts = "apple,banana;cherry".split("[,;]");
// ["apple", "banana", "cherry"]
- 替换操作
String result = "18812345678".replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
// 188****5678
- 复杂匹配验证
// 邮箱验证正则
String emailRegex = "^[\\w-]+(\\.[\\w-]+)*@([\\w-]+\\.)+[a-zA-Z]{2,7}$";
System.out.println("test@example.com".matches(emailRegex)); // true
五、高级应用示例
- 提取HTML内容
String html = "<div><h1>Title</h1><p>Content</p></div>";
Pattern tagPattern = Pattern.compile("<([a-zA-Z]+)>(.*?)</\\1>");
Matcher m = tagPattern.matcher(html);while(m.find()){System.out.println("标签:" + m.group(1) + " 内容:" + m.group(2));
}
// 输出:
// 标签:h1 内容:Title
// 标签:p 内容:Content
- 日志分析
String log = "2023-08-20 14:23:45 [INFO] User login: id=12345";
Pattern logPattern = Pattern.compile("(\\d{4}-\\d{2}-\\d{2}) " + // 日期"(\\d{2}:\\d{2}:\\d{2}) " + // 时间"\\[(\\w+)\\] " + // 日志级别"(.+)"); // 消息内容Matcher m = logPattern.matcher(log);
if(m.find()){System.out.println("时间:" + m.group(1) + " " + m.group(2));System.out.println("级别:" + m.group(3));System.out.println("消息:" + m.group(4));
}
六、性能优化建议
- 预编译Pattern对象
// 多次使用的正则应预编译
private static final Pattern DATE_PATTERN = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
- 避免过度回溯
// 差:(a+)*b
// 优:a+b
- 合理使用懒惰量词
// 匹配最短内容
<.*?> // 懒惰匹配
七、常见问题解决
- 中文匹配
String chineseRegex = "[\\u4e00-\\u9fa5]+";
System.out.println("中文测试".matches(chineseRegex)); // true
- 多行匹配模式
Pattern multiLine = Pattern.compile("^\\d+", Pattern.MULTILINE);
String input = "123\n456";
Matcher m = multiLine.matcher(input);
while(m.find()){System.out.println(m.group()); // 输出123和456
}
- 大小写不敏感
Pattern.compile("[a-z]+", Pattern.CASE_INSENSITIVE);
八、调试工具推荐
- 在线验证工具:regex101.com
- IDEA内置正则调试器
- Regex Tester插件
通过系统学习正则表达式,可以显著提升文本处理效率。建议从简单模式开始实践,逐步掌握复杂表达式编写技巧,同时注意特殊字符转义和性能优化问题。