We learned various ways to split string in Java. In this guide, we will see how to split string by multiple delimiters in Java.
Program to Split String by Multiple Delimiters
In this example, we have a string that contains multiple special characters, we want to split this string using these special characters as delimiters. We can do this by using regex, all the delimiters are specified inside brackets “[ ]
“. This regex is used inside split method of Java String class.
public class JavaExample { public static void main (String[] args) { //A string with multiple delimiters String str = "Text1,Text2#Text3 Text4:Text5.Text6"; //Specified the delimiters inside brackets, there is a //whitespace after # to consider space as delimiter as well String[] strArray = str.split("[,# :.]"); for(String s: strArray){ System.out.println(s); } } }
Output:
Text1 Text2 Text3 Text4 Text5 Text6
Multiple consecutive delimiters in a String
The above program is fine if the given string doesn’t contain the multiple consecutive delimiters, however if it does then the above solution would produce empty string, see the following program:
public class JavaExample { public static void main (String[] args) { //A string with multiple consecutive delimiters String str = "Text1,##::Text2"; //Specified the delimiters inside brackets String[] strArray = str.split("[,#:]"); for(String s: strArray){ System.out.println(s); } } }
Output: As you can see we have empty strings in the output, if you do not want this behaviour then see the next program where we have solution for this:
To avoid empty string use the regex shown in the following program:
public class JavaExample { public static void main (String[] args) { String str = "Text1,##::Text2"; //there is a + sign after closing bracket, this is //to consider consecutive delimiters as one String[] strArray = str.split("[,#:]+"); for(String s: strArray){ System.out.println(s); } } }
Output:
Related Programs: