我希望得到的子串
目前我使用这样的代码我希望得到的子串
while (fileName.endsWith(".csv")) {
fileName = fileName.substring(0, fileName.lastIndexOf(FILE_SUFFIX_CSV));
if (fileName.trim().isEmpty()) {
throw new IllegalArgumentException();
}
}
上面的代码工作正常时,用户指定小写字母的扩展名(.CSV),但Windows接受扩展大小写敏感的,所以他可以给像.CsV,.CSV等。我如何改变上面的代码?
在此先感谢
为什么不把它变成小写?
while (fileName.toLowerCase().endsWith(".csv")) {
fileName = fileName.substring(0, fileName.toLowerCase().lastIndexOf(FILE_SUFFIX_CSV));
if (fileName.trim().isEmpty()) {
throw new IllegalArgumentException();
}
}
'filename.lastIndexOf(。 ..)'有同样的问题。这也必须转换为小写。除此之外:这就是答案! – Seelenvirtuose 2014-09-25 05:56:51
@Seelenvirtuose这是答案,除非你需要在文件名中保存大小写,这很可能。 – 2014-09-25 05:58:29
@ThomasStets用'fileName.toLowerCase()。lastIndexOf(FILE_SUFFIX_CSV)'你不能改变变量。你只是在改变指数的计算。变量'fileName'仍被替换为_original_字符串('fileName.substring(...)')的子字符串。 – Seelenvirtuose 2014-09-25 05:59:51
您可以将两者都转换为大写。
因此改变这一行
fileName = fileName.substring(0, fileName.lastIndexOf(FILE_SUFFIX_CSV));
到
fileName = fileName.toUpperCase().substring(0, fileName.lastIndexOf(FILE_SUFFIX_CSV.toUpperCase()));
你可以试试这个方法
int lastIndexOfDot=fileName.lastIndexOf("\\.");
String fileExtension=fileName.substring(lastIndexOfDot+1,fileName.length());
while(fileExtension.equalsIgnoreCase(".csv")){
}
或者
while(fileName.toUpperCase().endsWith(".CSV"){}
请转换为小写,然后进行比较。
while (fileName.toLowerCase().endsWith(".csv")) {
fileName = fileName.toLowerCase().substring(0, fileName.toLowerCase().lastIndexOf(FILE_SUFFIX_CSV));
if (fileName.toLowerCase().trim().isEmpty()) {
throw new IllegalArgumentException();
}
}
深夜正则表达式的解决方案:
Pattern pattern = Pattern.compile(".csv", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(fileName);
while (matcher.find()) {
fileName = fileName.substring(0, matcher.start());
if (fileName.trim().isEmpty()) {
throw new IllegalArgumentException();
}
}
的Matcher
只会find()
一次。然后它可以将其可用的start
位置报告给substring
原始文件名。
将文件名转换为小写的花花公子 – 2014-09-25 05:54:54
这已经在这里得到了解答 - http://*.com/questions/13620555/case-sensitive-file-extension-and-existence-checking – 2014-09-25 06:04:12