Java String.split(String regex, int limit)

Syntax

String.split(String regex, int limit) has the following syntax.

public String [] split(String regex,  int limit)

Example

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


/* w ww.  j  ava  2s  .c  o m*/
public class Main {

  public static void main(String[] args) {
  
    String str = "test from java2s.com";
    String delimiters = "\\s+|,\\s*|\\.\\s*";

    String[] tokensVal = str.split(delimiters);

    System.out.println("Count of tokens = " + tokensVal.length);
    
    for(String token : tokensVal) {
      System.out.println(token);
    } 
    
    tokensVal = str.split(delimiters, 3);

    System.out.println("\nCount of tokens = " + tokensVal.length);
    
    for(String token : tokensVal) {
      System.out.println(token);
    }    
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    java.lang »




Boolean
Byte
Character
Class
Double
Enum
Float
Integer
Long
Math
Number
Object
Package
Process
ProcessBuilder
Runnable
Runtime
SecurityManager
Short
StackTraceElement
StrictMath
String
StringBuffer
StringBuilder
System
Thread
ThreadGroup
ThreadLocal
Throwable