Java 如何从文件名中提取数字后缀
在Java中,我有一个文件名示例ABC.12.txt.gz,我想从文件名中提取数字12。目前我正在使用上一个索引方法并多次提取子字符串。您可以尝试使用模式匹配Java 如何从文件名中提取数字后缀,java,Java,在Java中,我有一个文件名示例ABC.12.txt.gz,我想从文件名中提取数字12。目前我正在使用上一个索引方法并多次提取子字符串。您可以尝试使用模式匹配 import java.util.regex.Pattern; 导入java.util.regex.Matcher; // ... 其他特征 字符串fileName=“…”;//带数字扩展名的文件名 Pattern=Pattern.compile(“^.*(\\d+).*$”)//提取数字的模式 //然后尝试匹配 Matcher Matc
import java.util.regex.Pattern;
导入java.util.regex.Matcher;
// ... 其他特征
字符串fileName=“…”;//带数字扩展名的文件名
Pattern=Pattern.compile(“^.*(\\d+).*$”)//提取数字的模式
//然后尝试匹配
Matcher Matcher=pattern.Matcher(文件名);
字符串numberExt=“”;
if(matcher.matches()){
numberExt=匹配器组(1);
}否则{
//文件名中没有数字值。
}
//在这里用你的号码。
您可以使用正则表达式将每个数字部分与字母数字部分分开:
public static void main(String args[]) {
String str = "ABC.12.txt.gz";
String[] parts = str.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
// view the resulting parts
for (String s : parts) {
System.out.println(s);
}
// do what you want with those values...
}
然后取下你需要的部分,做你必须做的事情。我们可以使用类似的方法从字符串中提取数字
String fileName="ABC.12.txt.gz";
String numberOnly= fileName.replaceAll("[^0-9]", "");
考虑过使用正则表达式吗?您当前的方法有什么问题?它有用吗?那么你的问题是什么?你能把你当前的尝试作为一个代码示例吗?
String fileName="ABC.12.txt.gz";
String numberOnly= fileName.replaceAll("[^0-9]", "");