Home » Core Java » util » regex » Split a string into an array by regular expressions

About Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

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.

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