regex

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.

Byron Kiourtzoglou

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.
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button