Skip to content

Java split String by dot Example

Java split String by dot example shows how to split String by dot in Java. A dot (.) has a special meaning in the regular expression and it needs to be escaped before splitting a string by dot.

How to split String by dot in Java?

Consider below given variable which holds the file name containing the file name and the file extension separated by a dot (.) character.

In order to extract the name of the file from the variable, you will think of splitting it by dot and get the first element of an array to extract the same as given in the below example.


What went wrong? The split method accepts the regular expression pattern and splits the string around the matches of the given pattern. A dot (.) character has a special meaning in a regular expression (and it is called a metacharacter). It matches with any character of the string and we get empty array when we split the string by dot. Since the array is empty, accessing its first element by 0 index throws ArrayIndexOutOfBoundsException exception.

Then how to split by dot? Well, if we want to split by dot literal (instead of the metacharacter), we need to escape it like "\\.". Here is the example program.


We can also use the quote method of the Pattern class.

This method returns the literal pattern string for the specified pattern as given below.


This example is a part of the Java String tutorial and Java RegEx tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.