I wanted to get a sub string

I am currently using code like this

    while (fileName.endsWith(".csv")) {
        fileName = fileName.substring(0, fileName.lastIndexOf(FILE_SUFFIX_CSV));
        if (fileName.trim().isEmpty()) {
            throw new IllegalArgumentException();
        }
    }

      

The above code works fine when the user specifies the small letters extension (.csv). But windows accept extension is case sensitive, so it can give as .CsV, .CSV, etc., how can I change the above code?

Thanks in Advance

+3


source to share


6 answers


why don't you convert it to lowercase?



while (fileName.toLowerCase().endsWith(".csv")) {
    fileName = fileName.substring(0, fileName.toLowerCase().lastIndexOf(FILE_SUFFIX_CSV));
    if (fileName.trim().isEmpty()) {
        throw new IllegalArgumentException();
    }
}

      

+13


source


Solution for late night regex:

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

will be only find()

once. It can then report its position start

, which you can use for the substring

original filename.

+5


source


You can try this way

 int lastIndexOfDot=fileName.lastIndexOf("\\.");
 String fileExtension=fileName.substring(lastIndexOfDot+1,fileName.length()); 
 while(fileExtension.equalsIgnoreCase(".csv")){

 } 

      

Or

while(fileName.toUpperCase().endsWith(".CSV"){}

      

+4


source


Please convert to lower case and then compare.

  while (fileName.toLowerCase().endsWith(".csv")) {
        fileName = fileName.toLowerCase().substring(0, fileName.toLowerCase().lastIndexOf(FILE_SUFFIX_CSV));
        if (fileName.toLowerCase().trim().isEmpty()) {
            throw new IllegalArgumentException();
        }
    }

      

+4


source


You can convert both to uppercase.

So change this line

fileName = fileName.substring(0, fileName.lastIndexOf(FILE_SUFFIX_CSV));

      

to

fileName = fileName.toUpperCase().substring(0, fileName.lastIndexOf(FILE_SUFFIX_CSV.toUpperCase()));

      

+3


source


use this utility function:

public static boolean endsWithIgnoreCase(String str, String suffix)
{
    int suffixLength = suffix.length();
    return str.regionMatches(true, str.length() - suffixLength, suffix, 0, suffixLength);
}

      

now you can do:

while (endsWithIgnoreCase(fileName, ".csv")) {
    fileName = fileName.substring(0, fileName.toLowerCase().lastIndexOf(FILE_SUFFIX_CSV));
    if (fileName.trim().isEmpty()) {
        throw new IllegalArgumentException();
    }
}

      

0


source







All Articles