在特定模式之前拆分所有内容

时间:2017-03-25 06:29:34

标签: java regex string

我有一个字符串

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代码使用正则表达式(?<=)(?=@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);

它完成了这项工作但是有很多样板。有没有正则表达式,以便我可以一次性完成所有这些工作?

感谢。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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);
}