Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split Everything before a particular pattern

Tags:

java

string

regex

I have a String

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

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

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);

It does the job but there's a lot of boilerplate. Is there any regex so that I can do all this stuff in one shot?

Thanks.

like image 593
user7765409 Avatar asked Mar 25 '17 06:03

user7765409


People also ask

How do you split based on first occurrence?

Use the String. split() method with array destructuring to split a string only on the first occurrence of a character, e.g. const [first, ... rest] = str. split('-'); .

How do you get a substring before?

Use the substring() method to get the substring before a specific character, e.g. const before = str. substring(0, str. indexOf('_')); . The substring method will return a new string containing the part of the string before the specified character.

How do you split a string before a character?

Use the split() method to cut string before the character in Python. The split() method splits a string into a list.


1 Answers

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

DEMO

This is basically looking for pairs of ,\s followed by anything thats further followed by string @Team.

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
like image 183
Raman Sahasi Avatar answered Sep 19 '22 06:09

Raman Sahasi