Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this split() fail?

Tags:

java

split

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?

like image 792
etheros Avatar asked Oct 31 '09 10:10

etheros


People also ask

What does split () does in Java?

The split() method divides the string at the specified regex and returns an array of substrings.

What is RegEx split?

The RegEx Split processor provides a way to split up the data in an attribute into an array, using a regular expression to define where the splits should occur. Use RegEx Split to split up data where you need a more advanced way of splitting up the data than using delimiters.

What does split return if character not found?

split (separator, limit) , if the separator is not in the string, it returns a one-element array with the original string in it.

What happens when you split a string in Java?

The string split() method breaks a given string around matches of the given regular expression. After splitting against the given regular expression, this method returns a string array.


2 Answers

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("."))
like image 194
Ramon Avatar answered Oct 28 '22 10:10

Ramon


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.

like image 21
jitter Avatar answered Oct 28 '22 10:10

jitter