How to split a String with multiple delimiters in Java
Solution 1
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.
Solution 2
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.
Solution 3
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+");
Solution 4
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());
}
Related videos on Youtube
Venzentx
To be beautifully focused on one thing that matters.
Updated on September 15, 2022Comments
-
Venzentx about 1 year
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
-
Venzentx almost 11 yearsin your case, the first element in the array would be " " (space)
-
Venzentx almost 11 yearshow to put all the outputs into an array in this case please ?
-
Audrius Meškauskas almost 11 yearsString [] elements = new String[tok.countTokens()], then just use for loop to iterate over tokens.