这是另一种方法:
Integer.valueOf(s.replaceFirst(".*(assignment|lab)([0-9]+).*", "$2"));
例如:
String assignment = "C:\\projects\\assignment3\\test\\test.java";
String lab = "C:\\projects\\lab3\\test\\test.java";
String none = "C:\\projects\\test\\test.java";
try {
int assignmentNumber = Integer.valueOf(assignment.replaceFirst(".*(assignment|lab)([0-9]+).*", "$2"));
System.out.println(assignmentNumber);
} catch (NumberFormatException e) {
System.out.println("Can't find neither assignment nor lab");
}
try {
int labNumber = Integer.valueOf(lab.replaceFirst(".*(assignment|lab)([0-9]+).*", "$2"));
System.out.println(labNumber);
} catch (NumberFormatException e) {
System.out.println("Can't find neither assignment nor lab");
}
try {
int noneNumber = Integer.valueOf(none.replaceFirst(".*(assignment|lab)([0-9]+).*", "$2"));
System.out.println(noneNumber);
} catch (NumberFormatException e) {
System.out.println("Can't find neither assignment nor lab");
}
印刷:
3
3
Can't find neither assignment nor lab