Java String Split with ""." (Dot)
Problem:
Why does the following code throw an ArrayIndexOutOfBoundsException when attempting to split on a dot, but works when splitting on a slash:
String filename = "D:/some folder/001.docx"; String extensionRemoved = filename.split(".")[0];
versus:
String driveLetter = filename.split("/")[0];
Solution:
To split on a literal dot, the dot character must be escaped to avoid treating it as a regex pattern (any character):
String extensionRemoved = filename.split("\.")[0];
The double backslash (\) is necessary to create a single backslash in the regex string.
Additionally, an edge case occurs when the input string is just a dot (".") because splitting it on a dot results in an empty array. To prevent an ArrayIndexOutOfBoundsException in this case, use the overloaded split(regex, limit) method with a negative limit to disable the removal of trailing blanks:
String extensionRemoved = filename.split("\.", -1)[0];
The above is the detailed content of Java String Splitting: Why Does `split(\'.\')` Throw an `ArrayIndexOutOfBoundsException`?. For more information, please follow other related articles on the PHP Chinese website!