【问题标题】:Splitting a string java based on multiple delimiters基于多个分隔符拆分字符串java
【发布时间】:2014-04-10 17:21:32
【问题描述】:

我需要根据分隔符拆分字符串并将其分配给对象。我知道拆分功能,但我无法弄清楚如何为我的特定字符串执行此操作。

对象的格式为:

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

等等。

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

任何想法都将不胜感激。

【问题讨论】:

标签: java split


【解决方案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());

正则表达式可能可以调整为更准确(例如,处理空格),但它在示例中运行良好。

【讨论】:

  • 非常好。感谢“模式”课。我不知道
  • 欢迎您。 Java 中的正则表达式 API 并不理想,但它可以完成这项工作。还要检查this tutorial
【解决方案2】:

使用“]”作为分隔符怎么样? 如果你的结构严格如你所说,应该可以识别和拆分。

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

【讨论】:

    【解决方案3】:

    您将需要执行多次拆分。

    1. 用分隔符“]”分割(如其他 cmets 和答案中所述)。
    2. 对于每个结果字符串,用分隔符“:[”分割。
    3. 您需要清除最后一个条目(从步骤 1 中的拆分),因为它将以 ']' 结尾

    【讨论】:

      【解决方案4】:

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

      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());
              }
          }
      }
      

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

      【讨论】:

        【解决方案5】:

        试试这个

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

        【讨论】: