Splitting a Java String by Multiple Delimiters

06 May 2023 Balmiki Mandal 0 Core Java

Splitting a Java String by Multiple Delimiters

When working with strings in Java, you may need to split a string according to multiple delimiters. Whether you are parsing a comma-separated String or an HTML table, we will look at a few different approaches to splitting a String by multiple delimiters in Java.

1. Using Java Regex

One of the easiest and most efficient ways to split a String by multiple delimiters is to use regular expressions. In Java, we can use the String.split() method which takes a regular expression as a parameter. Let's take a simple example of splitting a String of words by commas and spaces.


String sample = "This, is a, sample String";
String[] words = sample.split("\\s*,\\s*");

The regular expression in this example, "\\s*,\\s*", will match one or more whitespaces followed by a comma, followed by one or more whitespaces. When the String.split() method is called, it will return an array of Strings that have been delimited by our specified pattern.

2. Using Apache Commons Text

Another option for splitting a Java String by multiple delimiters is to use the Commons Lang library from Apache. This library contains the StringUtils.splitByWholeSeparator() method which can be used to split a String using multiple delimiters. Here's a quick example to demonstrate how this method works:


String sample = "This; is a; sample String";
String[] words = StringUtils.splitByWholeSeparator(sample, "; ");

In this example, we are using the StringUtils.splitByWholeSeparator() method to split up our original String by a semicolon followed by a space. After this code has run, the words array will contain all of the split Strings.

Conclusion

In this article, we discussed two different approaches to splitting a Java String by multiple delimiters. We looked at using the String.split() method and the StringUtils.splitByWholeSeparator() method from the Apache Commons Lang library. Both approaches are easy to use and offer powerful ways to split up a String of words into individual elements.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.