Splitting up data file in Java Scanner

后端 未结 3 546
情歌与酒
情歌与酒 2021-01-21 15:42

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

相关标签:
3条回答
  • 2021-01-21 16:17

    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);
        }
    
    0 讨论(0)
  • 2021-01-21 16:20

    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();
      }
    
    0 讨论(0)
  • 2021-01-21 16:22

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题