Demonstrate the usage of the Pattern.split() method in Java

Java 8Object Oriented ProgrammingProgramming

The specified input sequence can be split around a particular match for a pattern using the java.util.regex.Pattern.split() method. This method has a single parameter i.e. the input sequence to split and it returns the string array obtained by splitting the input sequence around a particular match for a pattern.

A program that demonstrates the method Pattern.split() in Java regular expressions is given as follows:

Example

 Live Demo

import java.util.regex.Pattern;
public class Demo {
   public static void main(String[] args) {
      String regex = "_";
      String input = "Oranges_are_orange";
      System.out.println("Regex: " + regex);
      System.out.println("Input: " + input);
      Pattern p = Pattern.compile(regex);
      String[] str = p.split(input);
      System.out.println("\nThe split input is:");
      for (String s : str) {
         System.out.println(s);
      }
   }
}

Output

Regex: _
Input: Oranges_are_orange
The split input is:
Oranges
are
orange

Now let us understand the above program.

The regex and the input values are printed. Then the input sequence is split around the regex value using the Pattern.split() method. The split input is printed. A code snippet which demonstrates this is as follows:

String regex = "_";
String input = "Oranges_are_orange";
System.out.println("Regex: " + regex);
System.out.println("Input: " + input);
Pattern p = Pattern.compile(regex);
String[] str = p.split(input);
System.out.println("\nThe split input is:");
for(String s : str) {
   System.out.println(s);
}
raja
Published on 19-Feb-2019 07:27:12
Advertisements