开发者

Why does this split() fail?

开发者 https://www.devze.com 2022-12-10 02:31 出处:网络
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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消