插件窝 干货文章 Java正则表达式语法详解及实用示例大全

Java正则表达式语法详解及实用示例大全

Java正则表达式 正则语法 Pattern类 Matcher类 正则示例    来源:    2025-08-11

Java正则表达式语法详解

一、基础元字符

Java正则表达式核心元字符:

  • . 匹配任意单个字符
  • \d 匹配数字,等价于[0-9]
  • \w 匹配单词字符,等价于[a-zA-Z0-9_]
  • \s 匹配空白字符
  • ^ 匹配行首
  • $ 匹配行尾

二、量词示例

// 匹配3位数字
String regex1 = "\\d{3}";

// 匹配1个或多个a
String regex2 = "a+";

// 匹配0个或多个b
String regex3 = "b*";

// 匹配1-3位小写字母
String regex4 = "[a-z]{1,3}";

三、分组与捕获

// 提取日期中的年月日
String dateRegex = "(\\d{4})-(\\d{2})-(\\d{2})";
Pattern pattern = Pattern.compile(dateRegex);
Matcher matcher = pattern.matcher("2023-05-20");

if(matcher.find()) {
  System.out.println("年: " + matcher.group(1));
  System.out.println("月: " + matcher.group(2));
  System.out.println("日: " + matcher.group(3));
}

四、常用正则示例

// 验证邮箱
String emailRegex = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";

// 验证手机号
String phoneRegex = "^1[3-9]\\d{9}$";

// 提取HTML标签内容
String htmlRegex = "<([a-z]+)>(.*?)";

五、Pattern和Matcher类

Java正则表达式核心API:

// 基本使用流程
String text = "示例文本123";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(text);

while(m.find()) {
  System.out.println("找到数字: " + m.group());
}