Why does this split () fail?

I am trying to get the file name extension, but for some reason I cannot perform the split:

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

What am I doing wrong?

+5
source share
3 answers

split()accepts a regular expression (see split (java.lang.String) ), not a separator string to separate. A regular expression "."means "any single character" (see regex ), so it will be split into anything that will not remain on the list. To split into a literal dot, use:

file.getName().split("\\.")// \. escapes . in regex \\ escapes \ in Java.String

Pattern.quote(str) , str . ( ramon)

file.getName().split(Pattern.quote("."))
+21

, api-doc split(java.lang.String)

, , - .

split("\\.")

, \. escape- Java-. , javastring.

+5

String.split() , . . , \, :

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

You need one backslash to escape the dot, so the regex knows you need the actual dot. You need another backslash to avoid the first backslash, i.e. Say Java that you want to have a real backslash inside your string.

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

+4
source

All Articles