如何在动态文本中搜索特殊字符[]之间的字符串

时间:2016-06-02 18:50:03

标签: java

您能否告诉我如何才能列出[]个字符之间的字符串?例如,我有一个像

这样的字符串

5014 [228] 6:37a 6:522* 7:06a8 7:22a [229] 9:32b8 ...

我需要将[]之间的每个字符串添加到数组中。

1 个答案:

答案 0 :(得分:1)

第二次尝试,我希望这有效。 我没有时间用其他类型的字符串来测试它。

   String str = "5014 [228] 6:37a 6:522* 7:06a8 7:22a [229] 9:32b8";

    String[][] result = new String[2][2]; //You can change the size of the array by yourself, 
                                          //for that case 2 2 should be enough
                                          //you could make n 2 

    String[] data1;
    String[] data2;

    String output1 = ""; //for the number between the bracets
    String output2 = "";//for the numbers outside of the bracets

    char[] help1 = new char[str.length()];
    char[] help2 = new char[str.length()];
    Arrays.fill(help1, '0');
    Arrays.fill(help2, '0');


    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (c == '[') {
            while (c != ']') {
                i++;
                help1[i] = str.charAt(i);
                c = str.charAt(i);
            }
        }

        if(c == ']'){
            while (c != '[') {
                i++;
                if(i > str.length()-1){
                    break;
                }
                help2[i] = str.charAt(i);
                c = str.charAt(i);
            }
            i--;
        }
    }



    for (int i = 0; i < help1.length; i++) {
        if (help1[i] != '0') {
            output1 += help1[i];
        }
    }

    for (int i = 0; i < help1.length; i++) {
        if (help2[i] != '0') {
            output2 += help2[i];
        }
    }

     data1 = output1.split("\\]");
     data2 = output2.split("\\[");

     StringBuilder sb;

     for (int i = 0; i < data2.length; i++) {
         if(i == data2.length){
             sb = new StringBuilder(data2[i]);
             sb.deleteCharAt(0);
             data2[i] = sb.toString();
         }else{
             sb = new StringBuilder(data2[i]);
             sb.deleteCharAt(0);
             sb.deleteCharAt(data2[i].length()-2);
             data2[i] = sb.toString();
         }

    }

     for (int i = 0; i < data1.length; i++) {
         result[i][0] = data1[i];
         result[i][1] = data2[i];
    }
}