You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用SimpleDateFormat从含未知位置额外字符的字符串提取日期

从任意位置的字符串中提取指定格式的日期

要从任意位置包含额外字符的字符串中提取dd-MM-yyyy格式的日期,核心思路是先通过正则定位符合格式的子串,再用日期工具解析验证有效性,具体实现如下:

步骤说明

  1. 正则匹配定位日期子串:用正则表达式匹配字符串中符合两位数字-两位数字-四位数字格式的片段,快速从杂乱字符串中筛选出疑似日期的内容。
  2. 日期解析验证合法性:通过日期格式化工具解析匹配到的子串,过滤掉格式正确但实际无效的日期(比如02-30-2024这种不存在的日期)。

代码实现

方式一:使用传统SimpleDateFormat(兼容Java 8之前版本)

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateExtractor {
    public static void main(String[] args) {
        // 覆盖不同场景的测试用例
        String[] testStrings = {
            "file-09-01-2024",
            "file-09-01-2024-version1",
            "09-01-2024-index",
            "09-01-2024"
        };
        
        // 匹配dd-MM-yyyy格式的正则表达式
        String dateRegex = "\\d{2}-\\d{2}-\\d{4}";
        Pattern pattern = Pattern.compile(dateRegex);
        
        // 初始化日期格式化工具,关闭宽松模式避免解析无效日期
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        sdf.setLenient(false);
        
        for (String str : testStrings) {
            Matcher matcher = pattern.matcher(str);
            if (matcher.find()) {
                String dateStr = matcher.group();
                try {
                    Date date = sdf.parse(dateStr);
                    System.out.println("提取到的日期:" + sdf.format(date));
                } catch (Exception e) {
                    System.out.println("无效日期:" + dateStr);
                }
            } else {
                System.out.println("未找到符合格式的日期:" + str);
            }
        }
    }
}

方式二:使用Java 8+推荐的DateTimeFormatter(线程安全)

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class DateExtractor {
    public static void main(String[] args) {
        String[] testStrings = {
            "file-09-01-2024",
            "file-09-01-2024-version1",
            "09-01-2024-index",
            "09-01-2024"
        };
        
        String dateRegex = "\\d{2}-\\d{2}-\\d{4}";
        Pattern pattern = Pattern.compile(dateRegex);
        
        // 初始化线程安全的日期格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
        
        for (String str : testStrings) {
            Matcher matcher = pattern.matcher(str);
            if (matcher.find()) {
                String dateStr = matcher.group();
                try {
                    LocalDate date = LocalDate.parse(dateStr, formatter);
                    System.out.println("提取到的日期:" + date.format(formatter));
                } catch (DateTimeParseException e) {
                    System.out.println("无效日期:" + dateStr);
                }
            } else {
                System.out.println("未找到符合格式的日期:" + str);
            }
        }
    }
}

关键注意点

  • 正则仅匹配格式:正则\\d{2}-\\d{2}-\\d{4}只能筛选格式符合的子串,无法验证日期是否真实存在,必须配合日期解析工具做二次校验。
  • 区分YYYY和yyyy:日常日期解析请用yyyy(公历年),YYYY代表周年(Week Year),可能导致跨年周的日期解析错误。
  • 多日期场景处理:如果字符串中可能存在多个符合格式的日期,可将if (matcher.find())改为while (matcher.find())循环提取所有匹配结果。

内容的提问来源于stack exchange,提问作者Ignatyo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 18:09:58