java string split regex code example

Example 1: How to split a string in Java

String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556

Example 2: split method in java

public class SplitExample2 { 
    public static void main(String args[]) 
    { 
        String str = "My name is Chaitanya";
        //regular expression is a whitespace here 
        String[] arr = str.split(" "); 
  
        for (String s : arr) 
            System.out.println(s); 
    } 
}

Example 3: Regex split java

package com.tutorialspoint;

import java.lang.*;

public class StringDemo {

   public static void main(String[] args) {

      String str = "a d, m, i.n";
      String delimiters = "\\s+|,\\s*|\\.\\s*";

      // analyzing the string 
      String[] tokensVal = str.split(delimiters);

      // prints the number of tokens
      System.out.println("Count of tokens = " + tokensVal.length);
    
      for(String token : tokensVal) {
         System.out.print(token);
      } 
   }
}

Example 4: splitting using regex java

Pattern p = Pattern.compile("(\\d+)|([a-zA-Z]+)");
Matcher m = p.matcher("810LN15");
List<String> tokens = new LinkedList<String>();
while(m.find())
{
  String token = m.group( 1 ); //group 0 is always the entire match   
  tokens.add(token);
}
//now iterate through 'tokens' and check whether you have a number or text