Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a String with multiple delimiters in Java

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

like image 537
Venzentx Avatar asked Dec 12 '22 18:12

Venzentx


1 Answers

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.

like image 60
Audrius Meškauskas Avatar answered Jan 08 '23 23:01

Audrius Meškauskas