首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >即使在混沌字符串中也能找到YYYY的Java Regex。

即使在混沌字符串中也能找到YYYY的Java Regex。
EN

Stack Overflow用户
提问于 2014-02-10 11:15:20
回答 1查看 304关注 0票数 0

我需要一个正则表达式来查找文件名中的年份和月份值,这个值可能会变得非常混乱。这里的例子是"SuSa_Q2Factory_2012-08.xls“。我的雷克斯被激怒了,因为公司名称中的"2“,人们有时也会把它写进文件名。

目前,我的regex看起来如下:

代码语言:javascript
复制
// 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);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-10 11:28:44

您可以使用PatternMatcher类:

代码语言:javascript
复制
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部分是从哪里开始的)。您需要在正则表达式组中捕获monthyear,并使用Matcher.group(int)方法提取它们。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21675643

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档