Java String Handling RegEx

Java split String by dot Example

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

How to split String by dot in Java?

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

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


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

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


We can also use quote method of Pattern class.

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


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

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.