Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java string split with "." (dot) [duplicate]

Why does the second line of this code throw ArrayIndexOutOfBoundsException?

String filename = "D:/some folder/001.docx"; String extensionRemoved = filename.split(".")[0]; 

While this works:

String driveLetter = filename.split("/")[0]; 

I use Java 7.

like image 815
Ali Ismayilov Avatar asked Feb 12 '13 12:02

Ali Ismayilov


People also ask

Can we split a string with dot in Java?

To split a string with dot, use the split() method in Java. str. split("[.]", 0); The following is the complete example.

What does split \\ s+ do in Java?

split("\\s+") will split the string into string of array with separator as space or multiple spaces. \s+ is a regular expression for one or more spaces.

How do you split a string with double quotes?

Use method String. split() It returns an array of String, splitted by the character you specified.

How do you check if a string contains a dot in Java?

The easiest way is to check with a . contains() statement.


2 Answers

You need to escape the dot if you want to split on a literal dot:

String extensionRemoved = filename.split("\\.")[0]; 

Otherwise you are splitting on the regex ., which means "any character".
Note the double backslash needed to create a single backslash in the regex.


You're getting an ArrayIndexOutOfBoundsException because your input string is just a dot, ie ".", which is an edge case that produces an empty array when split on dot; split(regex) removes all trailing blanks from the result, but since splitting a dot on a dot leaves only two blanks, after trailing blanks are removed you're left with an empty array.

To avoid getting an ArrayIndexOutOfBoundsException for this edge case, use the overloaded version of split(regex, limit), which has a second parameter that is the size limit for the resulting array. When limit is negative, the behaviour of removing trailing blanks from the resulting array is disabled:

".".split("\\.", -1) // returns an array of two blanks, ie ["", ""] 

ie, when filename is just a dot ".", calling filename.split("\\.", -1)[0] will return a blank, but calling filename.split("\\.")[0] will throw an ArrayIndexOutOfBoundsException.

like image 143
Bohemian Avatar answered Sep 28 '22 11:09

Bohemian


The dot "." is a special character in java regex engine, so you have to use "\\." to escape this character:

final String extensionRemoved = filename.split("\\.")[0]; 
like image 28
aimhaj Avatar answered Sep 28 '22 11:09

aimhaj