我正在尝试使用正则表达式从字符串中提取2个日期 - 由于某种原因 - 正则表达式不提取日期 - 这是我的代码:
private String[] getDate(String desc) {
int count=0;
String[] allMatches = new String[2];
Matcher m = Pattern.compile("(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d(?:,)").matcher(desc);
while (m.find()) {
allMatches[count] = m.group();
}
return allMatches;
}
Run Code Online (Sandbox Code Playgroud)
我的字符串desc是:"coming from the 11/25/2009 to the 11/30/2009"
我得到一个空数组...
sp0*_*00m 11
你的正则表达式首先匹配日期和月份(DD/MM/YYYY),而输入则以月份和日期(MM/DD/YYYY)开头.
此外,您的日期必须后跟逗号匹配((?:,)部分).
这个应该适合您的需求:
(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d
Run Code Online (Sandbox Code Playgroud)

Debuggex图.
3个问题:
1)您正在尝试使用格式来解析日期dd/MM/YYYY格式MM/dd/YYYY.
2)你忘了count在while循环中增加.
3)(?:,)正则表达式末尾的部分是无用的.
此代码适用于我的计算机:
private static String[] getDate(String desc) {
int count=0;
String[] allMatches = new String[2];
Matcher m = Pattern.compile("(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d").matcher(desc);
while (m.find()) {
allMatches[count] = m.group();
count++;
}
return allMatches;
}
Run Code Online (Sandbox Code Playgroud)
测试:
public static void main(String[] args) throws Exception{
String[] dates = getDate("coming from the 25/11/2009 to the 30/11/2009");
System.out.println(dates[0]);
System.out.println(dates[1]);
}
Run Code Online (Sandbox Code Playgroud)
输出:
25/11/2009
30/11/2009
Run Code Online (Sandbox Code Playgroud)
您已经将月份的月份和日期倒退了,并且(?:,)在每个日期的末尾都需要使用逗号。尝试以下方法:
(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\\d\\d
Run Code Online (Sandbox Code Playgroud)