Skip to content

2026-08-27 · 正则表达式处理字符串、Path/Files 操作文件——两个实用工具。

Java 正则与文件

1. 正则表达式基础

正则 = 用特殊字符匹配字符串模式:

java
String text = "我的手机号是 13800138000,邮箱是 test@example.com";

// String 自带的正则方法
text.matches(".*138.*");     // true(是否匹配)
text.replaceAll("138\\d{8}", "139****"); // 替换手机号
text.split("\\s+");          // 按空格分割

常用正则符号

符号含义示例
.任意字符a.c 匹配 abc、a1c
\d数字 [0-9]\d{11} 匹配 11 位数字
\w字母/数字/下划线\w+ 匹配一个单词
\s空白字符\s+ 匹配一个或多个空格
*0 次或多次a* 匹配空串、a、aa
+1 次或多次a+ 匹配 a、aa(不匹配空串)
?0 次或 1 次a? 匹配空串、a
{n}恰好 n 次\d{3} 匹配 3 位数字
{n,m}n 到 m 次\d{3,5} 匹配 3-5 位数字
[abc]字符集[aeiou] 匹配元音
^ / $开头/结尾^\d+$ 整个字符串是数字

记忆:\d(数字)、\w(单词字符)、\s(空白)、+(一次以上)、*(零次以上)。

常用正则示例

java
// 手机号
String phoneRegex = "1[3-9]\\d{9}";

// 邮箱
String emailRegex = "[\\w.-]+@[\\w.-]+\\.\\w+";

// 身份证号
String idRegex = "\\d{17}[\\dXx]";

正则在数据校验(手机号、邮箱、身份证格式)中常用。Spring 的 @Pattern 注解校验就是用它。

2. Pattern 与 Matcher

需要"查找多个匹配"或"提取匹配内容"时用:

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

String text = "张三 13800138000,李四 13900139000";

// 编译正则
Pattern pattern = Pattern.compile("1[3-9]\\d{9}");

// 创建匹配器
Matcher matcher = pattern.matcher(text);

// 查找所有匹配
while (matcher.find()) {
    System.out.println("找到手机号:" + matcher.group());
}
// 输出:找到手机号:13800138000 / 找到手机号:13900139000

只做一次判断用 String.matches() 就够;要提取多个内容再用 Pattern/Matcher。

3. Path 与 Files(文件操作,推荐)

NIO 提供的文件操作 API,读写文件很方便:

java
import java.nio.file.Path;
import java.nio.file.Files;

// Path(路径)
Path path = Path.of("C:\\test\\hello.txt");  // Path.of 是简单写法
path.toAbsolutePath();  // 绝对路径
path.getFileName();     // 文件名

// Files(操作)
Files.exists(path);                    // 是否存在
Files.createFile(path);                // 创建文件
Files.createDirectories(Path.of("C:\\test\\newDir")); // 创建多级目录
Files.delete(path);                    // 删除

// 读写文件(最常用)
String content = Files.readString(path);                          // 读取全部
Files.writeString(path, "Hello World");                           // 写入字符串
Files.write(path, java.util.List.of("line1", "line2"));           // 写入多行

// 复制和移动
Files.copy(source, target);   // 复制
Files.move(source, target);   // 移动

日常文件读写用 Path + Files 就够了。旧的 java.io.File API 遇到能看懂即可,新代码不写。