使用" .splits#34分割字符串;但是在匹配数组中保留分隔符(字符串)

时间:2014-12-11 20:59:23

标签: java regex string split

我有这个字符串

"name={{0,0,0},{0,0,0},{0,0,0}}lastName={{0,0,0},{0,0,0},{0,0,0}}street[696]{{0,0,0},{0,0,0},{0,0,0}}OK

我想回到这个阵列:

['name={{0,0,0},{0,0,0},{0,0,0}}', 'lastName={{0,0,0},{0,0,0},{0,0,0}}', 'street[696]{{0,0,0},{0,0,0},{0,0,0}}', 'OK']

我试过这个:

String[] tokens = buffer.split("(?<=[a-zA-Z]+)");

但看起来jvm卡住了!

任何帮助?

2 个答案:

答案 0 :(得分:4)

您可以使用此正则表达式进行拆分:

(?!^)(?=\\b[a-zA-Z])

这个正则表达式意味着在不开始时和字边界后面有一个字母时分割。

<强>代码:

String s="name={{0,0,0},{0,0,0},{0,0,0}}lastName={{0,0,0},{0,0,0},{0,0,0}}street[696]{{0,0,0},{0,0,0},{0,0,0}}OK";
String[] toks = s.split( "(?!^)(?=\\b[a-zA-Z])" );
for (String tok: toks)
    System.out.printf("[%s]%n", tok);

输出:

[name={{0,0,0},{0,0,0},{0,0,0}}]
[lastName={{0,0,0},{0,0,0},{0,0,0}}]
[street[696]{{0,0,0},{0,0,0},{0,0,0}}]
[OK]

答案 1 :(得分:0)

//试试这个

字符串x =“name = {{0,0,0},{0,0,0},{0,0,0}} lastName = {{0,0,0},{0,0, 0},{0,0,0}}的街道[696] {{0,0,0},{0,0,0},{0,0,0}} OK“;

    String[] arr = x.split("}}");


    for(int i=0;i<arr.length-1;i++){
        arr[i]+="}";
    }

    //display
    for(int i=0;i<arr.length;i++){
        System.out.println(arr[i]);
    }