regex

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.

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
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button