Java正则表达式实战指南

Java 正则表达式详解

Java正则表达式实战指南_第1张图片

一、正则表达式概述

Java 中的正则表达式主要通过 java.util.regex 包中的两个类来实现:

  • Pattern:表示一个正则表达式模式
  • Matcher:用于匹配输入字符串和模式

二、基本使用场景及代码示例

1. 字符串匹配(是否完全匹配)

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexExample {
    public static void main(String[] args) {
        // 定义正则表达式:匹配6位数字
        String regex = "^\\d{6}$";
        
        // 编译正则表达式为 Pattern 对象
        Pattern pattern = Pattern.compile(regex);
        
        // 创建 Matcher 对象,传入要匹配的字符串
        Matcher matcher = pattern.matcher("123456");
        
        // 判断是否完全匹配
        boolean isMatch = matcher.matches();
        
        System.out.println("是否匹配: " + isMatch); // 输出: true
    }
}

2. 查找子串(搜索匹配内容)

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexExample {
    public static void main(String[] args) {
        // 定义正则表达式:匹配所有数字
        String regex = "\\d+";
        
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher("Hello 123 World 456");
        
        // 使用 find() 方法查找所有匹配项
        while (matcher.find()) {
            System.out.println("找到数字: " + matcher.group());
        }
        // 输出:
        // 找到数字: 123
        // 找到数字: 456
    }
}

3. 替换操作

public class RegexExample {
    public static void main(String[] args) {
        // 将所有连续空格替换为单个空格
        String input = "Hello   World,    this   is   a   test.";
        String result = input.replaceAll("\\s+", " ");
        
        System.out.println(result); 
        // 输出: Hello World, this is a test.
    }
}

4. 分割字符串

public class RegexExample {
    public static void main(String[] args) {
        // 按照非字母数字字符进行分割
        String input = "Hello,World!This-is_a.test";
        String[] parts = input.split("[^\\w]+");
        
        for (String part : parts) {
            System.out.println(part);
        }
        // 输出:
        // Hello
        // World
        // This
        // is
        // a
        // test
    }
}

5. 提取信息(捕获组)

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexExample {
    public static void main(String[] args) {
        // 匹配日期格式 YYYY-MM-DD,并提取年月日
        String input = "Today is 2023-09-15";
        String regex = "(\\d{4})-(\\d{2})-(\\d{2})";
        
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        
        if (matcher.find()) {
            System.out.println("完整日期: " + matcher.group(0)); // 输出: 2023-09-15
            System.out.println("年份: " + matcher.group(1));     // 输出: 2023
            System.out.println("月份: " + matcher.group(2));     // 输出: 09
            System.out.println("日期: " + matcher.group(3));     // 输出: 15
        }
    }
}

6. 验证邮箱格式

public class RegexExample {
    public static void main(String[] args) {
        String email = "[email protected]";
        String regex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
        
        boolean isValid = email.matches(regex);
        System.out.println("邮箱是否有效: " + isValid); // 输出: true
    }
}

7. 验证手机号码(中国大陆)

public class RegexExample {
    public static void main(String[] args) {
        String phone = "13812345678";
        String regex = "^1[3-9]\\d{9}$"; // 匹配以13-19开头的11位数字
        
        boolean isValid = phone.matches(regex);
        System.out.println("手机号是否有效: " + isValid); // 输出: true
    }
}

8. 验证密码强度(至少包含大小写字母和数字)

public class RegexExample {
    public static void main(String[] args) {
        String password = "Password123";
        // 至少一个大写字母、一个小写字母和一个数字,长度至少8位
        String regex = "^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).{8,}$";
        
        boolean isValid = password.matches(regex);
        System.out.println("密码是否符合要求: " + isValid); // 输出: true
    }
}

三、常用元字符和语法说明

元字符 描述 示例
. 匹配任意单个字符 "a.c" 可以匹配 “abc”、“a@c” 等
\d 匹配任意数字 [0-9] "\\d{3}" 匹配三位数字
\D 匹配非数字 "\\D+" 匹配一个或多个非数字
\w 匹配单词字符 [a-zA-Z0-9_] "\\w+" 匹配一个或多个单词字符
\W 匹配非单词字符 "\\W+" 匹配一个或多个非单词字符
\s 匹配空白字符 "\\s+" 匹配一个或多个空白
\S 匹配非空白字符 "\\S+" 匹配一个或多个非空白
^ 匹配字符串开始 "^abc" 表示以 “abc” 开头
$ 匹配字符串结束 "abc$" 表示以 “abc” 结尾
* 匹配前一个字符0次或多次 "go*gle" 可匹配 “ggle”、“google” 等
+ 匹配前一个字符1次或多次 "go+gle" 至少需要一个 o
? 匹配前一个字符0次或1次 "colou?r" 可匹配 “color” 或 “colour”
{n} 匹配前一个字符恰好 n 次 "\\d{3}" 匹配三位数字
{n,} 匹配前一个字符至少 n 次 "\\d{3,}" 匹配至少三位数字
{n,m} 匹配前一个字符至少 n 次,至多 m 次 "\\d{3,5}" 匹配3-5位数字
[] 匹配括号内的任意一个字符 "[aeiou]" 匹配任何一个元音字母
[^] 不匹配括号内的任意一个字符 "[^0-9]" 匹配非数字字符
() 捕获组,用于提取匹配的子串 `"([a-z]+)\.(txt

四、不同方法对比总结表

方法 功能 特点 适用场景
matches() 完全匹配 需要整个字符串匹配正则 验证输入格式(如邮箱、电话等)
find() 查找匹配 在字符串中查找所有匹配项 提取信息、搜索特定内容
replaceFirst() 替换第一个匹配项 只替换第一次出现的匹配 局部替换需求
replaceAll() 替换所有匹配项 替换所有符合条件的内容 格式化处理、清理数据
split() 分割字符串 根据正则表达式分割 解析复杂格式的数据
group() 获取捕获组 提取特定分组的内容 提取结构化数据(如日期、URL等)

五、最佳实践建议

场景 建议做法
输入验证 使用 matches(),确保整个字符串符合规范
数据提取 使用 find() 和捕获组获取所需信息
内容替换 根据需求选择 replaceFirst()replaceAll()
复杂解析 使用捕获组配合 group() 提取结构化数据
性能优化 对于重复使用的正则表达式,提前编译成 Pattern 对象
调试帮助 使用在线正则测试工具(如 regex101.com)调试表达式

通过掌握这些常见的使用场景和技巧,可以高效地在 Java 中应用正则表达式解决各种字符串处理问题。

你可能感兴趣的:(java基础,开发,正则表达式,java,正则表达式,开发语言)