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.
This question is related to
java
regex
string
split
indexoutofboundsexception
I believe you should escape the dot. Try:
String filename = "D:/some folder/001.docx";
String extensionRemoved = filename.split("\\.")[0];
Otherwise dot is interpreted as any character in regular expressions.
This is because .
is a reserved character in regular expression, representing any character.
Instead, we should use the following statement:
String extensionRemoved = filename.split("\\.")[0];
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];
I hope this helps
Source: Stackoverflow.com