Home » Core Java » util » regex » Split a string by regular expression

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 by regular expression

This is an example of how to split a String using regular expression. Splitting a String with a regular expression implies that you should:

  • Compile a given String regular expression to a Pattern, using compile(string regex) API method of Pattern. The given regular expression in the example is the String “ian”.
  • 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.
  • Print the array fields to check on the matches of the pattern.

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 RegExSplit {

    public static void main(String[] args) {

  String[] splits = Pattern.compile("ian").split("the darwinian devonian explodian chicken");

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


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

  }
    }
}

Output:

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

 
This was an example of how to split a String using regular expression 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