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


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("
The 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("
The split input is:"); for(String s : str) {    System.out.println(s); }

Vikyath Ram
Vikyath Ram

A born rival

Updated on: 30-Jul-2019

56 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements