regex

Split a string into an array by regular expressions

This is an example of how to split a string into an array by regular expressions. Splitting a string by regular expressions implies that you should:

  • Compile a String regular expression to a Pattern, using compile(String regex) API method of Pattern.
  • Split the given input sequence around matches of this pattern, using split(CharSequence input) API method of Pattern. The result of this method is a String array.
  • Print the elements of the array.

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

package com.javacodegeeks.snippets.core;

import java.util.regex.*;

/**
 * Split a String into a Java Array of Strings divided by an RE
 */

public class SplitString {

    public static void main(String[] args) {

  String[] x =


    Pattern.compile("ian").split("the darwinian devonian explodian chicken");

  for (int i = 0; i < x.length; i++) {


System.out.println(i + " "" + x[i] + """);

  }
    }
}

Output:

0 "the darwin"
1 " devon"
2 " explod"
3 " chicken"

  
This was an example of how to split a string into an array by regular expressions in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He 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
Inline Feedbacks
View all comments
Back to top button