Split everything to a specific template

I have a line

Jon, Kim, Hem, David, Gary, Bryan, Otis, Neil, Blake, Greg, @Team=Cowboys, Chargers, Panthersm, Royals, Kings, Warriors 

I want to split this line in java from all commas before @Team . The result should look like this:

 Jon Kim Hem David Gary Bryan Otis Neil Blake Greg @Team=Cowboys, Chargers, Panthersm, Royals, Kings, Warriors 

My java code uses regex (?<=)( ?=@Team ) :

 String data = "Jon, Kim, Hem, David, Gary, Bryan, Otis, Neil, Blake, Greg, @Team=Cowboys, Chargers, Panthersm, Royals, Kings, Warriors"; String arr[] = data.split("(?<=)( ?=@Team )"); String temp[] = arr[0].split(",\\s"); String result[] = new String[temp.length + 1]; int i=0; for(i=0; i<temp.length; i++) result[i] = temp[i]; result[i] = arr[1]; for(String s : result) System.out.println(s); 

He does the job, but there are many templates. Is there any regex so I can do it all in one shot?

Thanks.

+5
source share
3 answers

You can use regex ,\s(?=.*@Team)

Demo

This is basically looking for pairs ,\s , followed by everything followed by the @Team line.

code

 String data = "Jon, Kim, Hem, David, Gary, Bryan, Otis, Neil, Blake, Greg, @Team=Cowboys, Chargers, Panthersm, Royals, Kings, Warriors"; String arr[] = data.split(",\\s(?=.*@Team)"); for(String s : arr) { System.out.println(s); } 

Output

 Jon Kim Hem David Gary Bryan Otis Neil Blake Greg @Team=Cowboys, Chargers, Panthersm, Royals, Kings, Warriors 
+4
source

This will work for you:

 public static void main(String[] args) throws Exception { String s = "Jon, Kim, Hem, David, Gary, Bryan, Otis, Neil, Blake, Greg, @Team=Cowboys, Chargers, Panthersm, Royals, Kings, Warriors"; // SPlit based on comma and space as long as there is a "@Test" later in the string String[] arr = s.split(",\\s+(?=.*@Team)"); for (String str : arr) { System.out.println(str); } } 

O / P:

 Jon Kim Hem David Gary Bryan Otis Neil Blake Greg @Team=Cowboys, Chargers, Panthersm, Royals, Kings, Warriors 
+3
source

Another way to achieve this:

 List <String> splitString = new ArrayList<>(); //container for result String data = "Jon, Kim, Hem, David, Gary, Bryan, Otis, Neil, Blake, Greg, @Team=Cowboys, Chargers, Panthersm, Royals, Kings, Warriors"; while ((data.indexOf("@") != 1) ){//stop when @ is reached int index = data.indexOf(",");//location of first , splitString.add( data.substring(0,index) ); //add substring to list data = data.substring(index+1);//remove substring from data index = data.indexOf(","); } splitString.add(data); //add what left of data to result for(String s : splitString) {//output System.out.println(s); } 
+3
source

Source: https://habr.com/ru/post/1265901/


All Articles