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

基于多个分隔符拆分java字符串,java,split,Java,Split,我需要根据分隔符拆分字符串并将其分配给对象。我知道split函数,但我不知道如何为我的特定字符串执行它 对象的格式为: class Selections{ int n; ArrayList<Integer> choices; } 其中: 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 h

我需要根据分隔符拆分字符串并将其分配给对象。我知道split函数,但我不知道如何为我的特定字符串执行它

对象的格式为:

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

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
等等

我不能使用带“,”的拆分作为分隔符,因为[]中的单个对象和元素都用“,”分隔

如果您有任何想法,我们将不胜感激。

使用“],”作为分隔符如何? 如果你的结构严格按照你说的那样,它应该能够识别和分割


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

您需要执行多个拆分

  • 用分隔符“]”拆分(如其他注释和答案中所述)
  • 对于每个结果字符串,使用分隔符“:[”拆分
  • 您需要清理最后一个条目(来自步骤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());
    

    正则表达式可能可以调整为更精确(例如,处理空格),但在示例中效果很好。

    我不知道如何使用内置函数来实现这一点。我只需编写自己的拆分方法:

    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());
            }
        }
    }
    
    私有列表拆分(字符串s){
    私有列表节=新的ArrayList();
    私有布尔insideBracket=false;
    私有整数n=0;
    private List ints=new ArrayList();
    对于(int i=0;i
    你可能需要稍微修改一下。现在,如果一个数字有多个数字,它就不起作用。

    试试这个

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

    为什么不直接使用
    ],
    作为分隔符呢?要获得额外的积分,请使用一个正则表达式,该正则表达式仅在前面加上
    ]
    时才在
    上拆分。要实现@Gabe的建议,请查看中的“Lookarounds”部分,尤其是。非常好。感谢“模式”课程。我不知道,不客气。java中用于正则表达式的API并不理想,但它确实做到了这一点。也检查一下。
    
    while(true){
            int tmp=str.indexOf("]")+1;
            System.out.println(str.substring(0,tmp));
            if(tmp==str.length())
                break;
            str=str.substring(tmp+1);   
        }