Home » Core Java » util » regex » Split string example

About Byron Kiourtzoglou

Avatar photo
Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Split string example

This is an example of how to split a String. We will split a given String using the Pattern API. Splitting a given String implies that you should:

  • Read the given input String.
  • Compile a given String regular expression to a Pattern, using compile(string regex) API method of Pattern. The given regex in the example is the exclamation point.
  • Use split(CharSequence input) API method of Pattern to split the given input sequence around matches of this pattern. It returns an array of strings.
  • Use the asList(String... a) API method of Arrays to get a List backed by the array.
  • You can also use split(CharSequence input, int limit) API method of Pattern to split the given input sequence around matches of this pattern, using a limit parameter that controls the number of times the pattern is applied and therefore affects the length of the resulting array.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.util.Arrays;
import java.util.regex.Pattern;

public class SplitDemo {

  public static void main(String[] args) {
    String input = "This!!unusual use!!of exclamation!!points";
    System.out.println(Arrays.asList(Pattern.compile("!!").split(input)));
    // Only do the first three:
    System.out

  .println(Arrays.asList(Pattern.compile("!!").split(input, 3)));
    System.out.println(Arrays.asList("Aha! String has a split() built in!"

  .split(" ")));
  }
}

Output:

[This, unusual use, of exclamation, points]
[This, unusual use, of exclamation!!points]
[Aha!, String, has, a, split(), built, in!]

 
This was an example of how to split a String in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments