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
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();
}
}
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.
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"){}
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();
}
}
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()));
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();
}
}