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
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 to share
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 to share
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 to share