Java正则表达式,即使在混乱的字符串中也能找到YYYY-MM
我需要一个正则表达式来从可能变得非常混乱的文件名中查找年份和月份值。这里我的例子是“SuSa_Q2工厂_2012-08.xls”。我的正则表达式很恼火,因为人们有时也会在文件名中写入公司名称中的单个“2” 目前我的正则表达式如下所示:Java正则表达式,即使在混乱的字符串中也能找到YYYY-MM,java,regex,expression,Java,Regex,Expression,我需要一个正则表达式来从可能变得非常混乱的文件名中查找年份和月份值。这里我的例子是“SuSa_Q2工厂_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 yea
// 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);
}
您可以使用
模式
和匹配器
类:
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);
}
这将打印年=2012,月=8
您的代码不起作用,因为公司名称没有固定长度,硬编码的
子字符串
索引不起作用(您只是不知道月-年
字符串的一部分从哪里开始)。您需要在正则表达式组中捕获月
和年
,并使用Matcher.group(int)
方法提取它们。根本不需要在字符类中键入-
、\ucode>或
或除破折号和右括号以外的任何内容![-\.,]`是关于正则表达式的基础教程。(1) {1,2}
将匹配1或2个字符。(2) []
表示一个字符类。[0-9]{4}(\.\124;\-\ 124; u124;\)[0-9]{1,2}正如devnull告诉alreadydid的,你们真的读过这个问题吗?问题不在于1-2个数字,而在于公司名称。在正则表达式中使用{1,2}
会使子字符串代码失败,因此这也不是一个可行的建议。谢谢,这段代码很有效,而且显然是一种更好的方法。今天我学习了模式和匹配器:)