This post will explore different ways to split a string in Java using the dot (.), pipe (|) or dollar ($) or question mark (?) as a delimiter.

1. Using String.split() method

The standard solution is to use the split() method provided by the String class. It takes a regular expression as a delimiter and returns a string array.

Download  Run Code

 
If we run the above code, it doesn’t work as expected. This is because the split() method takes a regular expression, and the dot is a special character that matches any character in the regex. We can avoid this behavior by creating a regex that will represent a dot. There are several ways to do this, which are covered below in detail:

⮚ Using an escape character

We can make the above code work by escaping the dot character. An escape character invokes an alternative interpretation on the following characters of a string. In Java, the \ (backslash) is used to escape special characters. Note that Java follows the two backslash-escape styles.

Download  Run Code

⮚ Wrapping dot between \Q and \E

Another plausible way of escaping is using \Q to backslash all subsequent special characters and \E to end the expression.

Download  Run Code

Character Class

We can also use Character class in Java for escaping the dot (.), as shown below:

Download  Run Code

Pattern.quote()

Another good alternative is to use the Pattern.quote(), which returns a literal pattern string for the specified string.

Download  Run Code

2. Using Guava’s Splitter Class

We can use the Splitter class from the Guava library, as shown below, which returns an Iterable.

Download Code

3. Using Apache Commons Lang

We can also leverage the StringUtils.split() method of Apache Commons Lang library, which splits the string into an array using a specified delimiter.

Download Code

4. Using StringTokenizer Class

The StringTokenizer is a legacy class that allows breaking a string into tokens using a delimiter, as shown below:

Download  Run Code

That’s all about splitting a Java String using dot, dollar, or question mark as a delimiter.