How to Split String in Java using Regular Expression?


The split(String regex) method of the String class splits this string around matches of the given regular expression.

This method works in the same way as invoking the method i.e split(String regex, int limit) with the given expression and a limit argument of zero. Therefore, trailing empty strings are not included in the resulting array.

Example

Live Demo

import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str = "a d, m, i.n";
      String delimiters = "\s+|,\s*|\.\s*";

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

Output

Count of tokens = 5
admin

Updated on: 26-Feb-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements