我需要一个正则表达式来查找文件名中的年份和月份值,这个值可能会变得非常混乱。这里的例子是"SuSa_Q2Factory_2012-08.xls“。我的雷克斯被激怒了,因为公司名称中的"2“,人们有时也会把它写进文件名。
目前,我的regex看起来如下:
// 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);
}发布于 2014-02-10 11:28:44
您可以使用Pattern和Matcher类:
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索引也不能工作(您只是不知道字符串的month-year部分是从哪里开始的)。您需要在正则表达式组中捕获month和year,并使用Matcher.group(int)方法提取它们。
https://stackoverflow.com/questions/21675643
复制相似问题