Splitting up data file in Java Scanner

六月ゝ 毕业季﹏ 提交于 2019-12-02 06:04:07

问题


I have the following data which I want to split up.

(1,167,2,'LT2A',45,'Weekly','1,2,3,4,5,6,7,8,9,10,11,12,13'),

to obtain each of the values:

1
167
2
'LT2A'
45
'Weekly'
'1,2,3,4,5,6,7,8,9,10,11,12,13'

I am using the Scanner class to do that and with , as the delimiter. But I face problems due to the last string: ('1,2,3,4,5,6,7,8,9,10,11,12,13').

I would hence like some suggestions on how I could split this data.
I have also tried using ,' as the delimiter but the string contains data without ''.

The question is quite specific to my needs but I would appreciate if someone could give me suggestions on how I could split this data up.

Thanks!


回答1:


What best you can do for your case is First split it using " ' " and then split it using " " " delimiter. like following code:

String cc = "(1,167,2,'LT2A',45,'Weekly','1,2,3,4,5,6,7,8,9,10,11,12,13'),";

Scanner s = new Scanner(cc);
  try
  {
     while (s.hasNextLine())
     {
        String[] tokens = s.nextLine().split("'"); //split it using ' delimiter 
        for (int i = 0; i < tokens.length; i++)
        {
           String[] ss = tokens[i].split(","); // split it using " delimiter 
           // do the processing for tokens here
        }
     }
  }
  finally
  {
     s.close();
  }



回答2:


you can use simple logic for example:

    String str="1,167,2,'LT2A',45,'Weekly','1,2,3,4,5,6,7,8,9,10,11,12,13'";
    Scanner s = new Scanner(str);
    s.useDelimiter(",");
    while(s.hasNext())
    {
        String element = s.next();
        if(element.startsWith("'") && ! element.endsWith("'"))
        {
            while(s.hasNext())
            {
                element += "," + s.next();
                if(element.endsWith("'"))
                    break;
            }
        }
        System.out.println(element);
    }



回答3:


try

    String s = "1,167,2,'LT2A',45,'Weekly','1,2,3,4,5,6,7,8,9,10,11,12,13'";
    Scanner sc = new Scanner(s);
    sc.useDelimiter(",");
    while (sc.hasNext()) {
        String n = sc.next();
        if (n.startsWith("'") && !n.endsWith("'")) {
            n = n + sc.findInLine(".+?'");
        }
        System.out.println(n);
    }
}


来源:https://stackoverflow.com/questions/14214206/splitting-up-data-file-in-java-scanner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!