Home > Software engineering >  Split string into two diff substrings based on a keyword
Split string into two diff substrings based on a keyword

Time:05-19

So Im trying to split into different lines so it first line is:

Aaron123,Nesmith456,Bruno789,Cabo12,Jay21,Smith22 -- 1st line

Aaron12,Nesmith22,Bruno33,Cabo44,Jay55,Smith66 -- 2nd line

  String s1 =  ("Aaron123,Nesmith456,Bruno789,Cabo12,Jay21,Smith22,Aaron12,Nesmith22,Bruno33,Cabo44,Jay55,Smith66);
   String s[];
    s = s1.split("Aaron");
    System.out.print(s[0]);

After doing that code it splits the line but the aaron part of both lines are missing and actually splits into 3 line instead of 2 lines where first line is just empty for some reason so I need help fixing this

Wrong output I get:

123,Nesmith456,Bruno789,Cabo12,Jay21,Smith22

12,Nesmith22,Bruno33,Cabo44,Jay55,Smith66

The output I want:

Aaron123,Nesmith456,Bruno789,Cabo12,Jay21,Smith22 -- 1st line

Aaron12,Nesmith22,Bruno33,Cabo44,Jay55,Smith66 -- 2nd line

CodePudding user response:

We can phrase this actually as a split on ,(?=Aaron), which splits on comma which is followed by Aaron. Note that Aaron will not be consumed during the split because we use a lookahead.

String s1 = "Aaron123,Nesmith456,Bruno789,Cabo12,Jay21,Smith22,Aaron12,Nesmith22,Bruno33,Cabo44,Jay55,Smith66";
String[] parts = s1.split(",(?=Aaron)");
System.out.println(Arrays.toString(parts));

This prints:

[Aaron123,Nesmith456,Bruno789,Cabo12,Jay21,Smith22,
 Aaron12,Nesmith22,Bruno33,Cabo44,Jay55,Smith66]

CodePudding user response:

Use a positive lookahead. You actually want it to split on "," but only if the text after the comma is "Aaron". The corresponding regular expression is ,(?=Aaron) where the (?= ) part means "check that the following text is this, but without incorporating it into the match".

s = s1.split(",(?=Aaron)");
  • Related