即使在混乱的字符串中也能找到YYYY-MM的Java Regex

时间:2014-02-10 11:15:20

标签: java regex expression

我需要一个正则表达式来查找文件名中可能变得非常混乱的年份和月份值。我的例子是“SuSa_Q2Factory_2012-08.xls”。由于公司名称中的单个“2”,人们有时也会写入文件名,因此我的正则表达式变得恼火。

目前我的正则表达式看起来像这样:

// Search for date of the Format 2012-02 / YYYY-MM
if (fileName.matches("[0-9]{4}[\\-\\_\\.\\,\\ ][0-9]{2}\\.(xls|xlsx)")) {
int year = Integer.parseInt(fileName.substring(0, 4));
int month = Integer.parseInt(fileName.substring(5, 7));
return new Month(year, month);
}

// Search for date of the Format 2012-2 / YYYY-M
if (fileName.matches("[0-9]{4}[\\-\\_\\.\\,\\ ][0-9]\\.(xls|xlsx)")) {
int year = Integer.parseInt(fileName.substring(0, 4));
int month = Integer.parseInt(fileName.substring(5, 6));
return new Month(year, month);
}

1 个答案:

答案 0 :(得分:1)

您可以使用PatternMatcher类:

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

[...]

String fileName = "SuSa_Q2Factory_2012-08.xls";
Pattern p = Pattern.compile(".*([0-9]{4})[-_., ]([0-9]{1,2})\\.(xls|xlsx)");
Matcher m = p.matcher(fileName);
if (m.matches()) {
    int year = Integer.parseInt(m.group(1));
    int month = Integer.parseInt(m.group(2));
    System.out.printf("year = %d, month = %d\n", year, month);
}

这会打印year = 2012, month = 8

您的代码不起作用,因为公司名称没有固定的长度,并且硬编码的substring索引不会做(您只是不知道在哪里{{ 1}}部分字符串开始)。您需要在正则表达式组中捕获month-yearmonth,并使用year方法提取它们。