我需要什么样的正则表达式来解析这样的文件名:"Ab12_Cd9023-2000-12-04-No234.nekiRtt3434GGG"
,其中解析的元素是:"Ab12_Cd9023"
(名称),"2000"
(年),{{1} }(月),"12"
(日),"04"
(数字),"234"
(后缀)。序列始终相同:"nekiRtt3434GGG"
。
我想使用name-yyyy-MM-dd-NoNN.suffix
+ pattern
个对象来解决这个问题。
答案 0 :(得分:1)
这是我找到的最好看的解决方案:
private static final Pattern PATTERN = Pattern.compile("^(?<name>\\w+)-"
+ "(?<year>\\d{4})-"
+ "(?<month>\\d{2})-"
+ "(?<day>\\d{2})-"
+ "No(?<number>\\d+)."
+ "(?<suffix>\\w+)$");
Matcher m = PATTERN.matcher(file.getName());
if(!m.matches())
//some code if the pattern doesnt match
//this is how you acces the parsed strings:
m.group("year")
答案 1 :(得分:0)
这个正则表达式可以解决这个问题:
([a-bA-B0-9_])-([0-9]{4})-([0-9]{2})-([04]{2})-No(.+)\.(.+)$
如果您将此作为模式使用,则每个()表示您要捕获的字符串的一部分。
答案 2 :(得分:0)
这可行:
private static final Pattern PATTERN = Pattern.compile("^(.+)-([0-9]{4})-([0-9]{2})-([0-9]{2})-No(.+)\.(.+)$");
...
Matcher matcher = PATTERN.matcher(string);
if (matcher.matches()) {
String name = matcher.group(1);
int year = Integer.parseInt(matcher.group(2));
int month = Integer.parseInt(matcher.group(3));
int day = Integer.parseInt(matcher.group(4));
String number = matcher.group(5);
String suffix = matcher.group(6);
System.out.println("name: " + name);
System.out.println("year: " + year);
System.out.println("month: " + month);
System.out.println("day: " + day);
System.out.println("number: " + number);
System.out.println("suffix: " + suffix);
} else {
// error: does not match
}
答案 3 :(得分:0)
如果序列始终相同,为什么不简单地使用 - 或分割它。像这样:
String filename = "Ab12_Cd9023-2000-12-04-No234.nekiRtt3434GGG";
String[] parts = filename.split("-|\\.");
for(String p : parts)
System.out.println(p);