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.
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('-'); .
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.
Use the split() method to cut string before the character in Python. The split() method splits a string into a list.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With