tags:

views:

144

answers:

3

I'm trying to get the extension of a filename, but for some reason I can't make split work:

System.out.println(file.getName()); //gNVkN.png
System.out.println(file.getName().split(".").length); //0

What am I doing wrong?

+4  A: 

Maybe you should reread the api-doc for split(java.lang.String)

The string you pass in is a regex.

Try using

split("\\.")

You need the double backslash because \. is an invalid escape in a Java-string. So you need to escape the backslash itself in the javastring.

jitter
+3  A: 

String.split() asks for a regular expression in its parameter, and in regular expressions, . will match any character. To make it work, you need to add a \, like this:

System.out.println(file.getName().split("\\.").length);

You need one backslash to escape the dot, so the regex knows you want an actual dot. You need the other backslash to escape the first backslash, i.e. to tell Java you want to have an actual backslash inside your string.

Read the javadoc for String.split and regular expressions for more info.

jqno
+11  A: 

split() takes a regular expression, not a separator string to split by. The regular expression "." means "any single character", so it will split on anything. To split on a literal dot use:

file.getName().split("\\.")
Ramon
In general, you can use Pattern.quote(str)to obtain a regular expression that matches `str` literally.
Ramon
Great answer, thanks!
etheros
Did somebody said **Regex** :D http://xkcd.com/208/
Rakesh Juyal