简体   繁体   中英

Why does this split() fail?

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?

split() takes a regular expression (See split(java.lang.String) ), not a separator string to split by. The regular expression "." means "any single character" (See regex ), so it will split on anything leaving nothing in you list. To split on a literal dot use:

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

In general, you can use Pattern.quote(str) to obtain a regular expression that matches str literally. (suggested by ramon )

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

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.

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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM