Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

2 Answers
Vikyath Ram

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);
}

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.