How to split a String with multiple delimiters in Java

Venzentx picture Venzentx · Jan 13, 2013 · Viewed 17k times · Source

I am trying to have the desired outputs like this:

555
555
5555

by using codes:

public class Split {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    String phoneNumber = "(555) 555-5555";

    String[] splitNumberParts = phoneNumber.split(" |-");


    for(String part : splitNumberParts)
        System.out.println(part);

But dont know how to get rid of the "( )" from the first element.

Thanks in advance.

Regards

Answer

Audrius Meskauskas picture Audrius Meskauskas · Jan 13, 2013

StringTokenizer supports multiple delimiters that can be listed in a string as second parameter.

StringTokenizer tok = new StringTokenizer(phoneNumber, "()- ");
String a = tok.nextToken();
String b = tok.nextToken();
String c = tok.nextToken();

In your case, this will give a = 555, b = 555, c = 5555.