基于多个分隔符拆分字符串java

时间:2014-04-10 17:21:33

标签: java split

我需要根据分隔符拆分字符串并将其分配给对象。我知道split功能,但是我无法知道如何为我的特定字符串做这个。

对象的格式为:

class Selections{
int n;
ArrayList<Integer> choices;
}

字符串的格式为:

1:[1,3,2],2:[1],3:[4,3],4:[4,3]

其中:

1:[1,3,2] is an object with n=1 and Arraylist should have numbers 1,2,3. 
2:[1] is an object with n=2 and Arraylist should have number 1

等等。

我不能使用&#34;,&#34;作为分隔符,因为单个对象和[]中的元素由&#34;,&#34;分隔。

任何想法都会受到赞赏。

5 个答案:

答案 0 :(得分:1)

如何使用“],”作为分隔符? 如果你的结构与你说的完全一样,它应该能够识别和分裂。

(抱歉,我想留下评论,但我的声誉不允许)

答案 1 :(得分:1)

您可以使用正则表达式获得更强大的结果,如下所示:

String s = "1:[1,3,2],2:[1],3:[4,3],4:[4,3],5:[123,53,1231],123:[54,98,434]";
// commented one handles white spaces correctly
//Pattern p = Pattern.compile("[\\d]*\\s*:\\s*\\[((\\d*)(\\s*|\\s*,\\s*))*\\]");
Pattern p = Pattern.compile("[\\d]*:\\[((\\d*)(|,))*\\]");
Matcher matcher = p.matcher(s);

while (matcher.find())
  System.out.println(matcher.group());

可以将正则表达式调整为更准确(例如,处理空格),但在示例中它可以正常工作。

答案 2 :(得分:0)

您需要执行多次拆分。

  1. 使用分隔符&#34;]拆分,&#34; (如其他评论和答案中所述)。
  2. 对于每个结果字符串,使用分隔符&#34;分开:[&#34;。
  3. 您将需要清理最后一个条目(来自步骤1中的拆分),因为它将以&#39;]&#39;
  4. 结束

答案 3 :(得分:0)

我不知道如何使用内置函数。我只想写自己的分割方法:

private List<Sections> split(String s){
    private List<Sections> sections = new ArrayList<>();
    private boolean insideBracket = false;
    private int n = 0;
    private List<Integer> ints = new ArrayList<>();

    for (int i = 0; i < s.length(); i++){
        char c = s.charAt(i); 
        if(!insideBracket && !c.equals(':')){
            n = c.getNumericValue();
        } else if(c.equals('[')){
            insideBracket = true;
        } else if (c.equals(']')){
            insideBracket = false;
            sections.add(new Section(n, ints));
            ints = new ArrayList();
        } else if(insideBracket && !c.equals(',')){
            ints.add(c.getNumericValue());
        }
    }
}

您可能需要稍微修改一下。现在,如果一个数字有多个数字,它就不起作用。

答案 4 :(得分:0)

试试这个

while(true){
        int tmp=str.indexOf("]")+1;
        System.out.println(str.substring(0,tmp));
        if(tmp==str.length())
            break;
        str=str.substring(tmp+1);   
    }