2017-03-25 65 views
5

之前,我有一個字符串拆分一切特定模式

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

我想以前@Team出現此字符串在Java中所有逗號分割。結果應該是這樣的:

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

我的Java代碼使用正則表達式(?<=)([email protected])

String data = "Jon, Kim, Hem, David, Gary, Bryan, Otis, Neil, Blake, Greg, @Team=Cowboys, Chargers, Panthersm, Royals, Kings, Warriors"; 
String arr[] = data.split("(?<=)([email protected])"); 
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); 

它的工作,但有很多的樣板。有沒有任何正則表達式,以便我可以一次完成所有這些東西?

謝謝。

回答

4

您可以使用正則表達式,\s(?=.*@Team)

DEMO

這基本上是在尋找的,\s對其次是什麼,多數民衆贊成進一步其次是字符串@Team

代碼

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

輸出

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

如果沒有'@ Team'輸入,不會發生分裂的。 –

3

這會爲你工作:

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

另一種方式來實現這一目標:

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's left of data to result 

for(String s : splitString) {//output 
    System.out.println(s); 
}