1.复杂匹配规则解析
贪婪vs懒惰匹配
默认贪婪模式会匹配尽可能长的字符串:
String text = "abcxxxabc";
Pattern.compile("a.*c").matcher(text).find(); // 匹配整个字符串
使用问号启用懒惰模式:
Pattern.compile("a.*?c").matcher(text).find(); // 匹配"abc"
分组与反向引用
圆括号创建捕获组,\n引用前面分组:
String date = "2023-08-20";
Pattern pattern = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
Matcher matcher = pattern.matcher(date);
if (matcher.find()) {
System.out.println(matcher.group(1)); // 2023
}
前瞻后顾断言
(?=)正向肯定前瞻匹配后面跟着特定模式的位置:
// 匹配后面跟着"元"的数字
Pattern.compile("\\d+(?=元)").matcher("价格100元").find(); // 匹配100
(?!)正向否定前瞻排除特定模式:
// 匹配不是"元"结尾的数字
Pattern.compile("\\d+(?!元)").matcher("100美元").find(); // 匹配100
2. 实用示例合集
HTML内容提取
String html = "<div><p>Hello</p></div>";
Pattern tagPattern = Pattern.compile("<([a-z][a-z0-9]*)[^>]*>.*?</\\1>");
Matcher tagMatcher = tagPattern.matcher(html);
while (tagMatcher.find()) {
System.out.println(tagMatcher.group()); // 完整标签
}
密码强度验证
String password = "StrongPwd123";
// 要求:大小写字母、数字、特殊字符,8-20位
String regex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,20}$";
boolean isValid = password.matches(regex);
掌握这些复杂匹配规则后,您将能应对各种文本处理场景,大幅提升开发效率。
422

被折叠的 条评论
为什么被折叠?



