Java Data Type Tutorial - Java String.split(String regex)








Syntax

String.split(String regex) has the following syntax.

public String [] split(String regex)

Example

In the following code shows how to use String.split(String regex) method.

//w w  w  .  j a  v  a2  s.c  o  m
public class Main {

  public static void main(String[] args) {
  
    String str = "test from java2s.com";
    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.println(token);
    } 
  }
}

The code above generates the following result.