English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Pattern split() method and example in Java

from the java.util.regex packagePatternThe class is the compiled representation of a regular expression.

of this typesplit()The method accepts aCharSequenceAn object that takes the input string as a parameter and, on each match, it splits the given string into a new token and returns a string array that saves all tokens.

Example

import java.util.regex.Pattern;
public class SplitMethodExample {
   public static void main(String args[]) {
      //Regular Expression to Find Digits
      String regex = "(\\s)(\\d)(\\s)";
      String input = " 1 Name: Radha, age:25 2 Name: Ramu, age:32 3 Name: Rajev, age:45";
      //Compile Regular Expression
      Pattern pattern = Pattern.compile(regex);
      //Verify if a match occurs
      if(pattern.matcher(input).find())
         System.out.println("Given String contains digits");
      else
         System.out.println("Given String does not contain digits");
      //Split String
      String strArray[] = pattern.split(input);
      for(int i=0; i<strArray.length;++{
         System.out.println(strArray[i]);
      }
   }
}

Output Result

Given String contains digits
Name: Radha, age:25
Name: Ramu, age:32
Name: Rajev, age:45

This method also accepts an integer value, which represents the number of times the pattern is applied. That is, you can determine the length of the result array by specifying the limit value.

Example

import java.util.regex.Pattern;
public class SplitMethodExample {
   public static void main(String args[]) {
      //Regular Expression to Find Digits
      String regex = "(\\s)(\\d)(\\s)";
      String input = " 1 Name: Radha, age:25 2 Name: Ramu, age:32" + " 3 Name: Rajeev, age:45 4 Name: Raghu, age:35" + " 5 Name: Rahman, age:30";
      //Compile Regular Expression
      Pattern pattern = Pattern.compile(regex);
      //Verify if a match occurs
      if(pattern.matcher(input).find())
         System.out.println("Given String contains digits");
      else
         System.out.println("Given String does not contain digits");
      //Split String
      String strArray[] = pattern.split(input, ", "); 4);
      for(int i=0; i<strArray.length;++{
         System.out.println(strArray[i]);
      }
   }
}

Output Result

Given String contains digits
Name: Radha, age:25
Name: Ramu, age:32
Name: Rajeev, age:45 4 Name: Raghu, age:35 5 Name: Rahman, age:30