BM Balmiki Mandal 06 May 2023 22 views 0 comments Core Java

Splitting a Java String by Multiple Delimiters

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.

0 Comments

No comments yet, Be the first to comment.

Post a Comment

Please sign in to post a comment.

Related Posts

Unlock the Ins and Outs of JavaScript Engines and Runtimes

What is a JavaScript Engine? A JavaScript engine is a program or interpreter which executes JavaScript code....

BM Balmiki Mandal 05 Sep 2023
Implementing HMACSHA256 Algorithm in Java with Key

Introducing HMACSHA256 in Java with Key HMACSHA256 is an authentication algorithm designed to secure data, su...

BM Balmiki Mandal 30 Aug 2023
HMACSHA256 Java Example - Creating Secure Message Authentication

HMACSHA256 Java Example HMACSHA256 is an advanced encryption algorithm that allows developers to create encry...

BM Balmiki Mandal 30 Aug 2023