如何在正则表达式模式中使用String[]匹配两种日期格式
解决方案
要实现匹配两种日期格式(DDTTTTMMM 和 MMMDDTTTT),核心是将月份数组转换为正则表达式的可选分组,再组合出匹配两种格式的完整模式。
步骤1:生成月份匹配的正则片段
将你的月份数组通过|拼接,形成正则的多选分支,用括号包裹确保作为整体匹配:
String[] months = {"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"}; // 拼接成 JAN|FEB|...|DEC,再包裹括号作为分组 String monthRegex = "(" + String.join("|", months) + ")";
步骤2:构建完整正则表达式
结合两种格式的规则,用|合并两个分支,并添加^和$锚点确保整个字符串完全匹配(避免部分匹配的误判):
// 匹配 6位数字+月份 或者 月份+6位数字 String fullRegex = "^(\\d{6}" + monthRegex + "|" + monthRegex + "\\d{6})$";
\d{6}等价于[0-9]{6},简洁匹配6位数字(对应DDTTTT部分)^表示字符串开头,$表示字符串结尾,确保输入完全符合格式
完整代码示例
import java.util.regex.Pattern; import java.util.regex.Matcher; public class DatePatternMatcher { public static void main(String[] args) { String[] months = {"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"}; String monthRegex = "(" + String.join("|", months) + ")"; String fullRegex = "^(\\d{6}" + monthRegex + "|" + monthRegex + "\\d{6})$"; Pattern datePattern = Pattern.compile(fullRegex); // 测试用例 testInput(datePattern, "011150DEC"); // 匹配成功 testInput(datePattern, "DEC011150"); // 匹配成功 testInput(datePattern, "011150XYZ"); // 匹配失败(月份不存在) testInput(datePattern, "XYZ011150"); // 匹配失败(月份不存在) testInput(datePattern, "01115DEC"); // 匹配失败(数字不足6位) } private static void testInput(Pattern pattern, String input) { Matcher matcher = pattern.matcher(input); System.out.printf("输入: %s → 匹配结果: %b%n", input, matcher.matches()); } }
关键说明
- 如果需要支持大小写不敏感的月份(比如
dec或Dec),可以在编译正则时添加Pattern.CASE_INSENSITIVE标志:Pattern datePattern = Pattern.compile(fullRegex, Pattern.CASE_INSENSITIVE); - 括号的作用是将月份多选分支和前后的数字部分分隔开,保证正则逻辑正确。
内容的提问来源于stack exchange,提问作者Jeremy Cline
相关产品推荐
相关产品推荐

