2

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!

Sumit Singh
  • 15,743
  • 6
  • 59
  • 89
Butter Beer
  • 1,100
  • 3
  • 16
  • 32
  • http://stackoverflow.com/questions/1658538/regular-expression-replace-all-commas-between-double-quotes similar question – vels4j Jan 08 '13 at 12:31

2 Answers2

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);
    }
vishal_aim
  • 7,636
  • 1
  • 20
  • 23
1

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);
    }
}
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275