For something as simple as detecting if a dot is in the string, you don't really have to use a regex. String
API provides lastIndexOf(int)
method:
lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
If you go through the method documentation, you'll notice that:
(...) if no such character occurs in this string, then -1 is returned.
The String is searched backwards starting at the last character.
Basically, all you have to do is check if this method returns a value greater than -1
and it isn't the last character. For example:
public static boolean hasExtension(final String fileName) {
final int indexOfDot = fileName.indexOf('.');
// Checking if dot index is greater than 0 - omitting
// names without dot or starting with a dot.
return indexOfDot > 0 && indexOfDot < fileName.length() - 1;
}
public static String getExtension(final String fileName) {
return hasExtension(fileName) ?
// +1 in substring to strip the dot.
fileName.substring(fileName.lastIndexOf('.') + 1)
// Returning empty string if no extension.
: "";
}
"file.pdf"
will report as having an extension and return pdf
. "file"
, ".file"
and "file."
will report as extensionless.