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.
1 |
String strFileName = "noname.txt"; |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.javacodeexamples.stringexamples; public class StringSplitByDotExample { public static void main(String[] args) { String strFileName = "noname.txt"; String[] strParts = strFileName.split("."); System.out.println( strParts[0] ); } } |
Output
1 2 |
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at com.javacodeexamples.stringexamples.StringSplitByDotExample.main(StringSplitByDotExample.java:11) |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.javacodeexamples.stringexamples; public class StringSplitByDotExample { public static void main(String[] args) { String strFileName = "noname.txt"; String[] strParts = strFileName.split("\\."); System.out.println(“File Name is: ” + strParts[0]); } } |
Output
1 |
File Name is: noname |
We can also use the quote
method of the Pattern class.
1 |
public static String quote(String pattern) |
This method returns the literal pattern string for the specified pattern as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.javacodeexamples.stringexamples; import java.util.regex.Pattern; public class StringSplitByDotExample { public static void main(String[] args) { String strFileName = "noname.txt"; String[] strParts = strFileName.split( Pattern.quote(".") ); System.out.println("File name is: " + strParts[0]); System.out.println("File extension is: " + strParts[1]); } } |
Output
1 2 |
File name is: noname File extension is: txt |
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.