1

I have a string where the pattern has multiple occurrences. I want to split the string into 4 parts with pattern "multiplex" including the pattern(multiplex). I want to have 4 strings

String1 = Name to true

String2 = Multiplex to 1000

String3 = Multiplex to 200

String4 = Multiplex to true

String aaa = "Name:1/1, Network: true, ...(more data)... MPEG: true Multiplex: 0004, Transport Stream ID: 0, Bandwidth: 5000000,...(more data)... Reserved Bandwidth: 1000 Multiplex: 0002, Transport Stream ID: 0, Bandwidth: 5000000,...(more data).. Reserved Bandwidth: 200 Multiplex: 0008, Transport Stream ID: 0, Bandwidth: 5000000, Reserved Bandwidth: 100000,...(more data)...true

    Pattern pattern = Pattern.compile("Multiplex:"); 

    Matcher m = pattern.matcher(aaa); 

    while (m.find()) 

Ho do I divide the string into 4 parts including "Multiplex"?

c.r
  • 43
  • 8

1 Answers1

1

You can use a regex pattern with a positive lookahead,

public class MyClass {
    public static void main(String args[]) {
        String s = "Name:1/1, Network: true, ...(more data)... MPEG: true Multiplex: 0004, Transport Stream ID: 0, Bandwidth: 5000000,...(more data)... Reserved Bandwidth: 1000 Multiplex: 0002, Transport Stream ID: 0, Bandwidth: 5000000,...(more data).. Reserved Bandwidth: 200 Multiplex: 0008, Transport Stream ID: 0, Bandwidth: 5000000, Reserved Bandwidth: 100000,...(more data)...true";
        String[] arr = s.split("(?=Multiplex:)");

        for(String str : arr){
            System.out.println(str);
        }
    }
}

This regex (?=Multiplex:) matches an empty string which is followed by Multiplex:

mettleap
  • 1,390
  • 8
  • 17
  • It is already saved in the array named arr which is an array of String – mettleap Nov 02 '18 at 18:10
  • Here arr[0] has name to true. How do I separate the values by "," in each array as I will be using this stream into a hashmap – c.r Nov 02 '18 at 18:43
  • @c.r, in that case just use the split method again on individual array elements ... for eg. if you do `arr[0].split(",")` you will get a new array and the split this time will be around commas in your arr[0] string – mettleap Nov 02 '18 at 18:46