Eternal_Explorer
Eternal_Explorer

Reputation: 1145

Split a String by multiple delimiters in java

what is the possible way to split a String by multiple delimiters? Is StringTokenizer can help me out to achieve this?

String str="list1|10456103|10456102|10456121#list2|10456105|10456122";
String str="list1|10513846#list2|";
String str3="list1#list2|10509855";
String str4="list2|10481812|";
String str5="list1|10396496|";
String str6="list1#list2|";

So now I should be able to extract only the long values :

For Str1  Finallist=[10456103,10456102,10456121,10456105,10456122]
For Str2  Finallist=[10513846]     
For Str3  Finallist=[10509855]
For Str4  Finallist=[10481812]
For Str5  Finallist=[10396496]
For Str6  Finallist[] 

           

Upvotes: 1

Views: 80

Answers (2)

WJS
WJS

Reputation: 40034

For your consideration you can also convert them to a map of lists on the fly for later processing.

It works as follows:

  • Split each String on [|#]
  • filter on numbers only matching on \\d+
  • convert to a long
  • and save to a list

The LinkedHashMap simply preserves processing order in the final map. It is not really required for this to work.

String[] strings = { str1, str2,str3,str4,str5,str6 };
Map<String, List<Long>> map = IntStream
        .range(0, strings.length)
        .boxed()
        .collect(Collectors.toMap(i->"str"+(i+1),
                i->Arrays.stream(strings[i].split("[|#]"))
                        .filter(str->str.matches("\\d+"))
                        .map(Long::valueOf)
                        .collect(Collectors.toList()),
                        (a,b)->a, LinkedHashMap::new));

map.entrySet().forEach(System.out::println);

Prints

str1=[10456103, 10456102, 10456121, 10456105, 10456122]
str2=[10513846]
str3=[10509855]
str4=[10481812]
str5=[10396496]
str6=[]

Upvotes: 1

maha
maha

Reputation: 643

you can split them using the split method for String in java, then check if it's numeric or not.

the string is split by having # or | or , once or more than once.

then the split strings are tested to be numeric or not, as so:

    public static void main(String []args){
    String str="list1|10456103|10456102|10456121#list2|10456105|10456122";
    
    String arr[] = str.split("[|,#]+");
    
    for(String s: arr){
        try{
            int num=Integer.parseInt(s);
            System.out.println(num + " is a number"); //add to list
        }catch(Exception err) {
            System.out.println(s + " is not a number"); //don't add to list
        }
    }
 }

Upvotes: 1

Related Questions