我正在编写一些用于解析非常大的数据集中的日期的代码。我有以下正则表达式来匹配日期的不同变体
"(((0?[1-9]|1[012])(/|-)(0?[1-9]|[12][0-9]|3[01])(/|-))|"
+"((january|february|march|april|may|june|july|august|september|october|november|december)"
+ "\\s*(0?[1-9]|[12][0-9]|3[01])(th|rd|nd|st)?,*\\s*))((19|20)\\d\\d)"
匹配格式的日期'月dd,yyyy' mm / dd / yyyy'和' mm-dd-yyyy'。这适用于那些格式,但我现在遇到欧洲日期的日期,yyyy'格式。我尝试添加(\\ d {1,2})?在正则表达式的开头添加一个?正则表达式当前匹配部分之后的量词
"((\\d{1,2})?((0?[1-9]|1[012])(/|-)(0?[1-9]|[12][0-9]|3[01])(/|-))|"
+"((january|february|march|april|may|june|july|august|september|october|november|december)"
+ "\\s*(0?[1-9]|[12][0-9]|3[01])?(th|rd|nd|st)?,*\\s*))((19|20)\\d\\d)"
但这并不完全可行,因为它有时会在月份之前和之后捕获数字字符(例如,2013年1月15日及之后的#39;)有时也不会(' 2013年1月和#39; )。有没有办法确保捕获两者中的一个?
答案 0 :(得分:1)
根据您的要求为您提供一个Java实现(从输入文本中搜索日期):
String input = "which matches dates of format 'january 31, 1976', '9/18/2013', "
+ "and '11-20-1988'. This works fine for those formats, but I'm now encountering dates" +
"in the European '26th May, 2020' format. I tried adding (\\d{1,2})? at the"+
"beginning of the regex and adding a ? quantifier after the current day matching section of the regex as such";
String months_t = "(january|february|march|april|may|june|july|august|september|october|november|december)";
String months_d = "(1[012]|0?[1-9])";
String days_d = "(3[01]|[12][0-9]|0?[1-9])"; //"\\d{1,2}";
String year_d = "((19|20)\\d\\d)";
String days_d_a = "(" + days_d + "(th|rd|nd|st)?)";
// 'mm/dd/yyyy', and 'mm-dd-yyyy'
String regexp1 = "(" + months_d + "[/-]" + days_d + "[/-]"
+ year_d + ")";
// 'Month dd, yyyy', and 'dd Month, yyyy'
String regexp2 = "(((" + months_t + "\\s*" + days_d_a + ")|("
+ days_d_a + "\\s*" + months_t + "))[,\\s]+" + year_d + ")";
String regexp = "(?i)" + regexp1 + "|" + regexp2;
Pattern pMod = Pattern.compile(regexp);
Matcher mMod = pMod.matcher(input);
while (mMod.find()) {
System.out.println(mMod.group(0));
}
输出是:
january 31, 1976
9/18/2013
11-20-1988
26th May, 2020