Venzentx
Venzentx

Reputation: 487

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

Upvotes: 4

Views: 18269

Answers (4)

Audrius Meškauskas
Audrius Meškauskas

Reputation: 21748

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.

Upvotes: 7

Daniel Figueroa
Daniel Figueroa

Reputation: 10666

When you're using split java will return an array of string which is separated from where there was an occurence of the items which you provided, thus if you where to do a split like you are doing now, you could add something like this:

phoneNumber.split(" |-|\\(|\\) ");

But thats not very nice looking, now is it? So instead we can do something like this, which basically tells java to remove anything that isn't a number:

String[] splitNumberParts = phoneNumber.split("\\D+");

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213261

If you just want your digits in sequence, then you can probably make use of Pattern and Matcher class, to find all the substrings matching a particular pattern, in your case, \d+.

You would need to use Matcher#find() method to get all the substrings matching your pattern. And use Matcher#group() to print the substring matched.

Here's how you do it: -

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

// Create a Pattern object for your required Regex pattern
Pattern pattern = Pattern.compile("\\d+");

// Create a Matcher object for matching the above pattern in your string
Matcher matcher = pattern.matcher(phoneNumber);

// Use Matcher#find method to fetch all matching pattern.
while (matcher.find()) {
    System.out.println(matcher.group());
}

Upvotes: 1

Will
Will

Reputation: 6286

why not do a replace first?

String phoneNumber = "(555) 555-5555";
String cleaned = phoneNumber.replaceAll("[^0-9]",""); // "5555555555"

Then you can use substring to get the parts you want.

Upvotes: 4

Related Questions