Java: How to split Java String with delimeter comma, space, new line, tab ? [SOLVED]

Sometimes it is very important to split a string on a comma n t etc. This piece of code will help you with it.

import java.util.*;

 public class split{

  public  static void main ( String args[]) {
       // this is my string
	String s = "Java,	Programming	is ,,, fun do you agree? ."; split
	String regexp = "[\s,;\n\t]+"; // these are my delimiters
	String [] tokens; // here i will save tokens
	// length is 7 because i know that my string will consist of 7 tokens
	for(int i=0;i<7;i++){
		tokens = s.split(regexp);

 // tokens are: Java Programming is fun do you agree?

Check out more posts on “Useful Java Functions and Tutorials”

Thanks for installing the Bottom of every post plugin by Corey Salzano. Contact me if you need custom WordPress plugins or website design.

Anatoly Spektor

IT Consultant with 6 years experience in Software Development and IT Leadership. Participated in such projects as Eclipse IDE, Big Blue Button, Toronto 2015 Panam Games.

Join the Discussion

Your email address will not be published. Required fields are marked *


  1. jetcracker

    >> // length is 7 because i know that my string will consist of 7 tokens
    We never know =)

    1. Anatoly Spektor

      You are absolutely right, that’s why this function can be easily upgraded and “7” replaced by the variable, or for loop can be easily replaced by foreach loop. However, in my case i know how many tokes I have 🙂

    2. ds

      Yeah Yeah 🙂

  2. b2b

    use Apache Commons StringUtils.split(String text, String delimeters) dude and dont build own bicycle

  3. Anatoly Spektor

    b2b thanks for sharing !

    I don’t think that creating 18-line function is reinventing the wheel, its purpose is to show alternative way of solving the current problem.

    This function can be customized for any language that accepts regular expressions, unfortunately StringUtils is language-limited.

  4. stuff

    you need to move the line that calls split outside the for loop. As it is you split the line 7 times, when you only need to do it once.